code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
----------------- loai giao dich ----------------
if exists (select name from sysobjects where name like 'Proc_LoaiGiaoDich_GetById')
drop procedure Proc_LoaiGiaoDich_GetById
go
create PROC Proc_LoaiGiaoDich_GetById (@maLoaiGD int )
as
select * from LoaiGD
where MaLoaiGD=@maLoaiGD
go
Exec Proc_LoaiGiaoDich_GetById 1
go
| 11hca1-banking-system | trunk/Database/Procedure/Procedure/LoaiGD.sql | TSQL | asf20 | 341 |
-------------- lich su truy cap --------------
-----------Xem thong tin lich su truy cap----------
if exists (select name from sysobjects where name like 'Proc_LichSuTruyCap_GetById')
drop procedure Proc_LichSuTruyCap_GetById
go
create PROC Proc_LichSuTruyCap_GetById (@maLS int )
as
select * from LichSuTruyCap
where Ma = @maLS
go
Exec Proc_LichSuTruyCap_GetById 1
go
------------------------------------------------
------- them lich su truy cap-------------
if exists (select name from sysobjects where name like 'Proc_LichSuTruyCap_Add')
drop procedure Proc_LichSuTruyCap_Add
go
create PROC Proc_LichSuTruyCap_Add (@maTK int , @ngayTruyCap datetime)
as
insert into LichSuTruyCap(MaTK,NgayTruyCap)
values (@maTK,@ngayTruyCap)
go
Exec Proc_LichSuTruyCap_Add 1,'06/12/2004'
go
select * from LichSuTruyCap
go
---------------------------------------------
-------- Ma Tai khoan -------------------
if exists (select name from sysobjects where name like 'Proc_LichSuTruyCap_GetByMaTaiKhoan')
drop procedure Proc_LichSuTruyCap_GetByMaTaiKhoan
go
create PROC Proc_LichSuTruyCap_GetByMaTaiKhoan (@maTK int )
as
select * from LichSuTruyCap
where MaTK = @maTK
go
Exec Proc_LichSuTruyCap_GetByMaTaiKhoan 1
go
----------------------------------------------
----------------- tim lan truy cap gan nhat----------------------
if exists (select name from sysobjects where name like 'Proc_LichSuTruyCap_GetLastLoginByMaTaiKhoan')
drop procedure Proc_LichSuTruyCap_GetLastLoginByMaTaiKhoan
go
create PROC Proc_LichSuTruyCap_GetLastLoginByMaTaiKhoan(@maTK int )
as
select * from LichSuTruyCap where MaTK = @maTK
order by NgayTruyCap desc
go
Exec Proc_LichSuTruyCap_GetLastLoginByMaTaiKhoan 1
go
| 11hca1-banking-system | trunk/Database/Procedure/LichSuTruyCap.sql | TSQL | asf20 | 1,774 |
if exists (select name from sysobjects where name like 'XemATM')
drop procedure XemATM
go
create PROC XemATM
as
select * from ATM
go
exec XemATM | 11hca1-banking-system | trunk/Database/Procedure/ATM.sql | TSQL | asf20 | 159 |
if exists (select name from sysobjects where name like 'Proc_ChiTietLSVay_GetById')
drop procedure Proc_ChiTietLSVay_GetById
go
create PROC Proc_ChiTietLSVay_GetById (@maLSVay int )
as
select * from ChiTietLSVay
where @maLSVay= ChiTietLSVay.MaLSVay
go
Exec Proc_ChiTietLSVay_GetById 1
go
--------------------------------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLSVay_GetByMaNgayVDLS')
drop procedure Proc_ChiTietLSVay_GetByMaNgayVDLS
go
create PROC Proc_ChiTietLSVay_GetByMaNgayVDLS (@maNgayVDLS nvarchar )
as
select * from ChiTietLSVay
where @maNgayVDLS= ChiTietLSVay.MaNgayVDLS
go
--------------------------------------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLSVay_GetByMaKH')
drop procedure Proc_ChiTietLSVay_GetByMaKH
go
create PROC Proc_ChiTietLSVay_GetByMaKH (@maKH nvarchar )
as
select * from ChiTietLSVay
where @maKH= ChiTietLSVay.MaKH
go | 11hca1-banking-system | trunk/Database/Procedure/ChiTietLSVay.sql | TSQL | asf20 | 959 |
if exists (select name from sysobjects where name like 'Proc_LoaiKyHanLS_GetById')
drop procedure Proc_LoaiKyHanLS_GetById
go
create PROC Proc_LoaiKyHanLS_GetById (@maLoaiKyHanLS int )
as
select * from LoaiKyHanLS
where @maLoaiKyHanLS= LoaiKyHanLS.MaLoaiKHLS
go
Exec Proc_LoaiKyHanLS_GetById 1
go | 11hca1-banking-system | trunk/Database/Procedure/LoaiKyHanLS.sql | TSQL | asf20 | 312 |
---------------- loai tai khoan-----------------
---------- thong tin
if exists (select name from sysobjects where name like 'Proc_LoaiThe_GetById')
drop procedure Proc_LoaiThe_GetById
go
create PROC Proc_LoaiThe_GetById (@maLoai int )
as
select * from LoaiThe
where MaLoai = @maLoai
go
Exec Proc_LoaiThe_GetById 1
go
---------------- -----------------------------
-------- thongtin thong qua maloaiky han----------------
---------- thong tin khach hang
if exists (select name from sysobjects where name like 'Proc_LoaiThe_GetByMaLoaiTK')
drop procedure Proc_LoaiThe_GetByMaLoaiTK
go
create PROC Proc_LoaiThe_GetBymaLoaiTK(@maLoaiTK int )
as
select * from LoaiThe
where maLoaiTK= @maLoaiTK
go
Exec Proc_LoaiThe_GetBymaLoaiTK 5
go
| 11hca1-banking-system | trunk/Database/Procedure/LoaiThe.sql | TSQL | asf20 | 773 |
if exists (select name from sysobjects where name like 'Proc_TruSo_GetById')
drop procedure Proc_TruSo_GetById
go
create PROC Proc_TruSo_GetById (@maTruSo int )
as
select * from TruSo
where @maTruSo= TruSo.MaTruSo
go
Exec Proc_TruSo_GetById 1
go
----------------------------------------
if exists (select name from sysobjects where name like 'Proc_TruSo_GetALL')
drop procedure Proc_TruSo_GetALL
go
create PROC Proc_TruSo_GetALL ( @delFlg int )
as
select * from TruSo
where @delFlg = DelFlg
go
Exec Proc_TruSo_GetALL 0
go
| 11hca1-banking-system | trunk/Database/Procedure/TruSo.sql | TSQL | asf20 | 559 |
---------------------- Loai tien -----------------
-------------- xem thong tin loai tien thong qua ma id ----------------
if exists (select name from sysobjects where name like 'Proc_LoaiTien_GetById')
drop procedure Proc_LoaiTien_GetById
go
create PROC Proc_LoaiTien_GetById (@maLoaiTien int )
as
select * from LoaiTien
where MaLoaiTien = @maLoaiTien
go
Exec Proc_LoaiTien_GetById 1
go | 11hca1-banking-system | trunk/Database/Procedure/LoaiTien.sql | TSQL | asf20 | 405 |
---------------- loai tai khoan-----------------
---------- thong tin
if exists (select name from sysobjects where name like 'Proc_LoaiTaiKhoan_GetById')
drop procedure Proc_LoaiTaiKhoan_GetById
go
create PROC Proc_LoaiTaiKhoan_GetById (@maLoaiTK int )
as
select * from LoaiTaiKhoan
where MaLoaiTK = @maLoaiTK
go
Exec Proc_LoaiTaiKhoan_GetById 1
go
---------------- -----------------------------
-------- thongtin thong qua maloaiky han----------------
---------- thong tin khach hang
if exists (select name from sysobjects where name like 'Proc_LoaiTaiKhoan_GetByMaLoaiKyHan')
drop procedure Proc_LoaiTaiKhoan_GetByMaLoaiKyHan
go
create PROC Proc_LoaiTaiKhoan_GetByMaLoaiKyHan (@maLoaiKyHan int )
as
select * from LoaiTaiKhoan
where MaLoaiKyHan = @maLoaiKyHan
go
Exec Proc_LoaiTaiKhoan_GetByMaLoaiKyHan 1
go
| 11hca1-banking-system | trunk/Database/Procedure/LoaiTaiKhoan.sql | TSQL | asf20 | 852 |
if exists (select name from sysobjects where name like 'Proc_TKKyHan_GetById')
drop procedure Proc_TKKyHan_GetById
go
create PROC Proc_TKKyHan_GetById (@maLoai int )
as
select * from TKKyHan
where @maLoai= TKKyHan.MaLoai
go
Exec Proc_TKKyHan_GetById 1
go
--------------------------------
--------------Xem thong tin ky han thong qua ten -----------------------
if exists (select name from sysobjects where name like 'Proc_TKKyHan_GetByTen')
drop procedure Proc_TKKyHan_GetByTen
go
create PROC Proc_TKKyHan_GetByTen (@ma nvarchar )
as
select * from TKKyHan
where @ma= TKKyHan.Ten
go
| 11hca1-banking-system | trunk/Database/Procedure/TKKyHan.sql | TSQL | asf20 | 618 |
------------- tai khoan tiet kiem ----------------
-------------- Thong Tin tai khoan tiet kiem --------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTietKiem_GetById')
drop procedure Proc_TaiKhoanTietKiem_GetById
go
create PROC Proc_TaiKhoanTietKiem_GetById (@maTKTK int )
as
select * from TaiKhoanTietKiem
where MaTKTietKiem = @maTKTK
go
Exec Proc_TaiKhoanTietKiem_GetById 1
go
------------------xem thong tin tai khoan tiet kiem qua ma tai khoan chinh ------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTietKiem_GetByMaTKChinh')
drop procedure Proc_TaiKhoanTietKiem_GetByMaTKChinh
go
create PROC Proc_TaiKhoanTietKiem_GetByMaTKChinh (@maTKChinh int )
as
select * from TaiKhoanTietKiem
where MaTKChinh = @maTKChinh
go
Exec Proc_TaiKhoanTietKiem_GetByMaTKChinh 1
go
------------------------- xem thong tin tai khoan tiet kiem qua ma loai tk---------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTietKiem_GetByMaLoaiTK')
drop procedure Proc_TaiKhoanTietKiem_GetByMaLoaiTK
go
create PROC Proc_TaiKhoanTietKiem_GetByMaLoaiTK (@maLoaiTK int )
as
select * from TaiKhoanTietKiem
where MaLoaiTK = @maLoaiTK
go
Exec Proc_TaiKhoanTietKiem_GetByMaLoaiTK 1
go
---------------- xem thong tin chi tiet lai suat ---------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTietKiem_GetByMaChiTietLS')
drop procedure Proc_TaiKhoanTietKiem_GetByMaChiTietLS
go
create PROC Proc_TaiKhoanTietKiem_GetByMaChiTietLS (@maChiTietLS int )
as
select * from TaiKhoanTietKiem
where MaChiTietLS = @maChiTietLS
go
Exec Proc_TaiKhoanTietKiem_GetByMaChiTietLS 1
go
| 11hca1-banking-system | trunk/Database/Procedure/TaiKhoanTietKiem.sql | TSQL | asf20 | 1,741 |
-------------- store pro khach hang -------------------
if exists (select name from sysobjects where name like 'Proc_LoaiKH_GetById')
drop procedure Proc_LoaiKH_GetById
go
create PROC Proc_LoaiKH_GetById (@maLoaiKH int )
as
select * from LoaiKH
where @maLoaiKH= LoaiKH.MaLoai
go
Exec Proc_LoaiKH_GetById 1
go
----------------------------------------
if exists (select name from sysobjects where name like 'Proc_LoaiKH_GetALL')
drop procedure Proc_LoaiKH_GetALL
go
create PROC Proc_LoaiKH_GetALL ( @delFlg int )
as
select * from LoaiKH
where @delFlg = DelFlg
go
Exec Proc_LoaiKH_GetALL 0
go
| 11hca1-banking-system | trunk/Database/Procedure/LoaiKH.sql | TSQL | asf20 | 628 |
---------------- chi tiet lai suat --------------
----------- xem chi tiet lai suat------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLaiSuat_GetById')
drop procedure Proc_ChiTietLaiSuat_GetById
go
create PROC Proc_ChiTietLaiSuat_GetById (@maChiTietLS int )
as
select * from ChiTietLaiSuat
where MaChiTietLS = @maChiTietLS
go
Exec Proc_ChiTietLaiSuat_GetById 1
go
--------------------------------------------
---------- xem thong tin lai suat qua ki han lai suat---------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLaiSuat_GetByMaLoaiKH')
drop procedure Proc_ChiTietLaiSuat_GetByMaLoaiKH
go
create PROC Proc_ChiTietLaiSuat_GetByMaLoaiKH (@maLoaiKH int )
as
select * from ChiTietLaiSuat
where MaLoaiKHLS = @maLoaiKH
go
Exec Proc_ChiTietLaiSuat_GetByMaLoaiKH 1
go
----------------------------------------------------------------
------------- xem thong tin lai suat thong qua ma ngay van dung ------------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLaiSuat_GetByMaNgayVDLS')
drop procedure Proc_ChiTietLaiSuat_GetByMaNgayVDLS
go
create PROC Proc_ChiTietLaiSuat_GetByMaNgayVDLS(@maNgayVDLS int )
as
select * from ChiTietLaiSuat
where MaNgayVDLS = @maNgayVDLS
go
Exec Proc_ChiTietLaiSuat_GetByMaNgayVDLS 1
go
---------------------------------------------------------------
------------- xem thong tin chi tiet lai suat thong qua loai tien---------------
if exists (select name from sysobjects where name like 'Proc_ChiTietLaiSuat_GetByMaLoaiTien')
drop procedure Proc_ChiTietLaiSuat_GetByMaLoaiTien
go
create PROC Proc_ChiTietLaiSuat_GetByMaLoaiTien(@maLoaiTien int )
as
select * from ChiTietLaiSuat
where LoaiTien = @maLoaiTien
go
Exec Proc_ChiTietLaiSuat_GetByMaLoaiTien 1
go
| 11hca1-banking-system | trunk/Database/Procedure/ChiTietLaiSuat.sql | TSQL | asf20 | 1,849 |
if exists (select name from sysobjects where name like 'XemTruSo')
drop procedure XemTruSo
go
create PROC XemTruSo
as
select * from TruSo
go
exec XemTruSo | 11hca1-banking-system | trunk/Database/Procedure/XemTruSo.sql | TSQL | asf20 | 169 |
if exists (select name from sysobjects where name like 'Proc_TaiKhoanVay_GetById')
drop procedure Proc_TaiKhoanVay_GetById
go
create PROC Proc_TaiKhoanVay_GetById (@maTKVay int )
as
select * from TaiKhoanVay
where @maTKVay= TaiKhoanVay.MaTKVay
go
Exec Proc_TaiKhoanVay_GetById 1
go
--------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanVay_GetByMaLSVay')
drop procedure Proc_TaiKhoanVay_GetByMaLSVay
go
create PROC Proc_TaiKhoanVay_GetByMaTKVay (@maLSVay nvarchar )
as
select * from TaiKhoanVay
where @maLSVay= TaiKhoanVay.MaLSVay
go
------------------------------------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanVay_LoaiTien')
drop procedure Proc_TaiKhoanVay_GetLoaiTien
go
create PROC Proc_TaiKhoanVay_GetByLoaiTien (@maLoaiTien int )
as
select * from TaiKhoanVay
where @maLoaiTien= TaiKhoanVay.MaLoaiTien
go
Exec Proc_TaiKhoanVay_GetById 1
go
--------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanVay_GetByMaLoaiTK')
drop procedure Proc_TaiKhoanVay_GetByMaLoaiTK
go
create PROC Proc_TaiKhoanVay_GetByMaLoaiTK (@maLoaiTK nvarchar )
as
select * from TaiKhoanVay
where @maLoaiTK= TaiKhoanVay.MaLoaiTK
go
----------------------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanVay_GetByTKChinh')
drop procedure Proc_TaiKhoanVay_GetByMaTKChinh
go
create PROC Proc_TaiKhoanVay_GetByMaTKChinh (@maTKChinh int )
as
select * from TaiKhoanVay
where @maTKChinh= TaiKhoanVay.MaTKChinh
go
Exec Proc_TaiKhoanVay_GetById 1
go
--------------------------------------
| 11hca1-banking-system | trunk/Database/Procedure/TaiKhoanVay.sql | TSQL | asf20 | 1,752 |
-----------------------------Tai khoan the--------------------
-------------Thong tin tai khoan the--------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_GetById')
drop procedure Proc_TaiKhoanThe_GetById
go
create PROC Proc_TaiKhoanThe_GetById (@maTKT int )
as
select * from TaiKhoanThe
where MaTaiKhoanThe = @maTKT
go
Exec Proc_TaiKhoanThe_GetById 1
go
-------------------- -----------------------------
------------- Update tai khoan the-------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_Update')
drop procedure Proc_TaiKhoanThe_Update
go
create PROC Proc_TaiKhoanThe_Update (@maTKThe int, @maTKChinh int,@soDu float ,@LSuat float , @MaLoaiThe int ,@LockFlg int
, @DelFlg int , @MaLoaiTien int, @MaLoaiTK int )
as
Update TaiKhoanThe
set MaTkChinh= @maTKChinh , SoDu= @soDu , LaiSuat= @LSuat,
MaLoaiThe= @MaLoaiThe ,LockFlg= @LockFlg , DelFlg=@DelFlg, MaLoaiTien = @MaLoaiTien ,MaLoaiTK= @MaLoaiTK
where MaTaiKhoanThe= @maTKThe
go
-------------------------------------
------------- tim tai khoan chinh the ma---------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_GetByMaTaiKhoanChinh')
drop procedure Proc_TaiKhoanThe_GetByMaTaiKhoanChinh
go
create PROC Proc_TaiKhoanThe_GetByMaTaiKhoanChinh (@maTK int )
as
select * from TaiKhoanThe
where MaTkChinh = @maTK
go
Exec Proc_TaiKhoanThe_GetByMaTaiKhoanChinh 1
go | 11hca1-banking-system | trunk/Database/Procedure/TaiKhoanThe.sql | TSQL | asf20 | 1,508 |
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTC_GetById')
drop procedure Proc_TaiKhoanTC_GetById
go
create PROC Proc_TaiKhoanTC_GetById (@maTKThe int )
as
select * from TaiKhoanTC
where @maTKThe= TaiKhoanTC.MaTKTheChap
go
Exec Proc_TaiKhoanTC_GetById 1
go
--------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTC_GetByMaTKVay')
drop procedure Proc_TaiKhoanTC_GetByMaTKVay
go
create PROC Proc_TaiKhoanTC_GetByMaTKVay (@maTKVay nvarchar )
as
select * from TaiKhoanTC
where @maTKVay= TaiKhoanTC.MaTKVay
go
--------------------------------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTC_GetByMaLoaiTK')
drop procedure Proc_TaiKhoanTC_GetByMaLoaiTK
go
create PROC Proc_TaiKhoanTC_GetByMaLoaiTK (@maLoaiTK nvarchar )
as
select * from TaiKhoanTC
where @maLoaiTK= TaiKhoanTC.MaLoaiTK
go | 11hca1-banking-system | trunk/Database/Procedure/TaiKhoanTC.sql | TSQL | asf20 | 937 |
---------- thong tin khach hang
if exists (select name from sysobjects where name like 'Proc_LoaiTruSo_GetById')
drop procedure Proc_LoaiTruSo_GetById
go
create PROC Proc_LoaiTruSo_GetById (@maTruSo int )
as
select * from LoaiTruSo
where MaLoaiTruSo = @maTruSo
go
Exec Proc_LoaiTruSo_GetById 1
go
| 11hca1-banking-system | trunk/Database/Procedure/LoaiTruSo.sql | TSQL | asf20 | 315 |
------------------ GiaoDich--------------
------------ thongtin giao dich ------------
if exists (select name from sysobjects where name like 'Proc_GiaoDich_GetById')
drop procedure Proc_GiaoDich_GetById
go
create PROC Proc_GiaoDich_GetById (@maGD int )
as
select * from GiaoDich
where GiaoDich.MaGD = @maGD
go
Exec Proc_GiaoDich_GetById 1
go
select * from GiaoDich
------------------------------
-----------update giao dich-------------
if exists (select name from sysobjects where name like 'Proc_GiaoDich_Update')
drop procedure Proc_GiaoDich_Update
go
create PROC Proc_GiaoDich_Update (@maGD int ,@maTKThe int ,@loaiGD int , @ngayGD datetime ,
@diaChi nvarchar (50), @soTienGD int , @noiDung nvarchar, @maTKNhan int, @maNganHang int, @maNV int, @trangThai int)
as
Update GiaoDich
set MaTKThe= @maTKThe ,LoaiGD= @loaiGD, NgayGD= @ngayGD, DiaChiGD= @diaChi, SoTienGD=@soTienGD,
NoiDungGD= @noiDung, MaTKNhan= @maTKNhan, MaNganHang= @maNganHang, MaNVGD=@maNV , TrangThaiGD=@trangThai
where @maGD= MaGD
go
------------------------------
-----------------Them giao dich----------------
if exists (select name from sysobjects where name like 'Proc_GiaoDich_Add')
drop procedure Proc_GiaoDich_Add
go
create PROC Proc_GiaoDich_Add (@maTKThe int ,@loaiGD int , @ngayGD datetime ,
@diaChi nvarchar (50), @soTienGD int , @noiDung nvarchar, @maTKNhan int, @maNganHang int, @maNV int, @trangThai int)
as
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,MaTKNhan,NoiDungGD ,MaNganHang,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD ,
@diaChi , @soTienGD , @noiDung , @maTKNhan , @maNganHang , @maNV, @trangThai)
go
select * from GiaoDich
go
| 11hca1-banking-system | trunk/Database/Procedure/GiaoDich.sql | TSQL | asf20 | 1,743 |
-------------------- Ngay Van dung Lai suat -------------------
----------- xem thong tin ngay van dung lai suat ------------------------
if exists (select name from sysobjects where name like 'Proc_NgayVDLS_GetById')
drop procedure Proc_NgayVDLS_GetById
go
create PROC Proc_NgayVDLS_GetById (@maNgayVDLS int )
as
select * from NgayVDLS
where MaNgayVDLS = @maNgayVDLS
go
Exec Proc_NgayVDLS_GetById 1
go
------------- xem thong tin ngay van dung lai suat thong qua ma nhan vien -------------
if exists (select name from sysobjects where name like 'Proc_NgayVDLS_GetByMaNV')
drop procedure Proc_NgayVDLS_GetByMaNV
go
create PROC Proc_NgayVDLS_GetByMaNV (@maNV int )
as
select * from NgayVDLS
where MaNV = @maNV
go
Exec Proc_NgayVDLS_GetByMaNV 1
go | 11hca1-banking-system | trunk/Database/Procedure/NgayVDLS.sql | TSQL | asf20 | 783 |
----------------- loai giao dich ----------------
if exists (select name from sysobjects where name like 'Proc_LoaiGiaoDich_GetById')
drop procedure Proc_LoaiGiaoDich_GetById
go
create PROC Proc_LoaiGiaoDich_GetById (@maLoaiGD int )
as
select * from LoaiGD
where MaLoaiGD=@maLoaiGD
go
Exec Proc_LoaiGiaoDich_GetById 1
go
| 11hca1-banking-system | trunk/Database/Procedure/LoaiGD.sql | TSQL | asf20 | 341 |
if exists (select name from sysobjects where name like 'Proc_ChucVu_GetALL')
drop procedure Proc_ChucVu_GetALL
go
create PROC Proc_ChucVu_GetALL (@type int)
as
if(@type =1)--- dirty read
begin
begin tran
set tran isolation level read uncommitted
select * from ChucVu where DelFlg=0
commit tran
end
else
begin
begin tran
set transaction isolation level repeatable read
select * from ChucVu where DelFlg=0
waitfor delay '00:00:10'
select * from ChucVu where DelFlg=0
commit tran
end
go
Exec Proc_ChucVu_GetALL 2
go
select * from ChucVu
----------------------------------
if exists (select name from sysobjects where name like 'Proc_ChucVu_GetById')
drop procedure Proc_ChucVu_GetById
go
create PROC Proc_ChucVu_GetById (@maChucVu int)
as
select * from ChucVu
where MaChucVu = @maChucVu
go
Exec Proc_ChucVu_GetById 1
go
------------------------
select * from ChucVu
--------------------
if exists (select name from sysobjects where name like 'Proc_ChucVu_GetDelFlg')
drop procedure Proc_ChucVu_GetDelFlg
go
create PROC Proc_ChucVu_GetDelFlg
as
select DelFlg from ChucVu
group by DelFlg
go
Exec Proc_ChucVu_GetDelFlg
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/Yen/ChucVu.sql | TSQL | asf20 | 1,207 |
if exists (select name from sysobjects where name like 'sp_ChucVu_DelID')
drop procedure sp_ChucVu_DelID
go
create proc sp_ChucVu_DelID(@machucvu int, @type int)
as
if(@type = 1)
begin
begin tran
update ChucVu set DelFlg=1 where MaChucVu=@machucvu
waitfor delay '00:00:10'
rollback
end
else
begin
begin tran
Update ChucVu set DelFlg=1 where MaChucVu=@machucvu
commit tran
end
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/Yen/ChucVuUnrepeatable.sql | TSQL | asf20 | 418 |
if exists (select name from sysobjects where name like 'Proc_NhanVien_Update')
drop procedure Proc_NhanVien_Update
go
create PROC Proc_NhanVien_Update (@maNV int,@ten nvarchar(50),@cmnd int,@moTa nchar(10),
@ngaySinh datetime, @diaChi nvarchar(50), @SoDT char(10) )
as
if Exists (select maKH
from KhachHang where @maNV= MaKH )
set tran isolation level read committed
begin tran
Update NhanVien
set TenNV= @ten,CMND = @cmnd, MoTa = @moTa, NgaySinh = @ngaySinh, DiaChi= @diaChi
where MaNV =@maNV
return 1
rollback
go
--------------------------------------------
if exists (select name from sysobjects where name like 'Proc_XemNhanVien')
drop procedure Proc_XemNhanVien
go
create PROC Proc_XemNhanVien
as
set tran isolation level read committed
begin tran
select * from NhanVien
commit tran
go | 11hca1-banking-system | trunk/Database/Procedure_Error/NhanVien.sql | TSQL | asf20 | 848 |
---------------- chi tiet lai suat --------------
if exists (select name from sysobjects where name like 'Proc_LaiSuat_Update')
drop procedure Proc_LaiSuat_Update
go
create PROC Proc_LaiSuat_Update (@mucLaiSuat float,@loaiTien int,@lastUpdate datetime)
as
set tran isolation level read committed
begin tran
Update ChiTietLaiSuat
set MucLS=@mucLaiSuat, LoaiTien=@loaiTien, LastUpdate=@lastUpdate
return 1
waitfor delay '00:00:10'
go
------------------------
if exists (select name from sysobjects where name like 'Proc_LaiSuat_XemLaiSuat')
drop procedure Proc_LaiSuat_XemLaiSuat
go
create PROC Proc_LaiSuat_XemLaiSuat
as
set tran isolation level read committed
begin tran
select * from ChiTietLaiSuat
commit tran
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/ChiTietLaiSuat.sql | TSQL | asf20 | 766 |
if exists (select name from sysobjects where name like 'Proc_TyGia_Update')
drop procedure Proc_TyGia_Update
go
create PROC Proc_TyGia_Update (@matien int,@sec int,@chuyenKhoan int,@ban int,@lastUpdate datetime)
as
set tran isolation level read committed
begin tran
Update TyGia
set Ban=@ban, ChuyenKhoan=@chuyenKhoan, MaLoaiTien=@matien, LastUpdate=@lastUpdate
return 1
rollback
go
------------------------
if exists (select name from sysobjects where name like 'Proc_TyGia_XemTyGia')
drop procedure Proc_TyGia_XemTyGia
go
create PROC Proc_TyGia_XemTyGia
as
set tran isolation level read committed
begin tran
select lt.TenTien, tg.Sec, tg.ChuyenKhoan, tg.Ban, tg.LastUpdate from TyGia tg, LoaiTien lt where tg.MaLoaiTien = lt.MaLoaiTien
commit tran
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/TyGia.sql | TSQL | asf20 | 799 |
-----------------------------Tai khoan the--------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_UpdateSodu')
drop procedure Proc_TaiKhoanThe_UpdateSodu
go
create PROC Proc_TaiKhoanThe_UpdateSodu (@maTKThe int,@soDu float)
as
set tran isolation level read committed
begin tran
Update TaiKhoanThe
set SoDu= @soDu
where MaTaiKhoanThe= @maTKThe
rollback
go
------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_XemSodu')
drop procedure Proc_TaiKhoanThe_XemSodu
go
create PROC Proc_TaiKhoanThe_XemSodu (@maTKThe int)
as
set tran isolation level read committed
begin tran
select * from TaiKhoanThe
where MaTaiKhoanThe= @maTKThe
commit tran
go | 11hca1-banking-system | trunk/Database/Procedure_Error/TaiKhoanThe.sql | TSQL | asf20 | 765 |
if exists (select name from sysobjects where name like 'Proc_ChiTietThe_Update')
drop procedure Proc_ChiTietThe_Update
go
create PROC Proc_ChiTietThe_Update (@lockF int,@delF int , @maSoPin nchar (10))
as
set tran isolation level read committed
begin tran
Update ChiTietThe
set MaSoPin=@maSoPin, LockFlg=@lockF, DelFlg=@delF
return 1
waitfor delay '00:00:10'
go
------------------------
if exists (select name from sysobjects where name like 'Proc_ChiTietThe_View')
drop procedure Proc_ChiTietThe_View
go
create PROC Proc_ChiTietThe_View
as
begin
select * from ChiTietThe
go
-------------------------
if exists (select name from sysobjects where name like 'Proc_ChiTietThe_KTMapin')
drop procedure Proc_ChiTietThe_KTMapin
go
create PROC Proc_ChiTietThe_KTMapin (@maPin nvarchar(50), @maThe int)
as
set tran isolation level read committed
begin tran
select * from ChiTietThe
where MaSoPin = @maPin and MaThe = @maThe
commit tran
go | 11hca1-banking-system | trunk/Database/Procedure_Error/ChiTietThe.sql | TSQL | asf20 | 986 |
------------------- Khach Hang-----------------
--------Update------------
if exists (select name from sysobjects where name like 'Proc_KhachHang_Update')
drop procedure Proc_KhachHang_Update
go
create PROC Proc_KhachHang_Update (@maKH int,@ten nvarchar(50),@cmnd int,@passPost nchar(10),
@ngaySinh datetime, @diaChi nvarchar(50),@maSoThue nchar(50), @giayPhep nchar (10),@nguoiDaiDien nvarchar (50), @SoDT char(10) )
as
set tran isolation level read committed
begin tran
Update KhachHang
set Ten= @ten,CMND = @cmnd, PassPost = @passPost, NgaySinh = @ngaySinh, DiaChi= @diaChi,
MaSoThue = @maSoThue, GiayPhepKinhDoanh = @giayPhep, NguoiDaiDien= @nguoiDaiDien, SoDT=@SoDT
where MaKH =@maKH
rollback
go
Exec Proc_KhachHang_Update 1,'Khanh',12345,'123H','05/02/2012','12 NND','354','MN123','thien','1234567890'
go
select *
from KhachHang
go
--------View------------
if exists (select name from sysobjects where name like 'sp_DSLoaiKH')
drop procedure sp_DSLoaiKH
go
create proc sp_DSLoaiKH
as
begin
select * from LoaiKH where DelFlg=0
end
go
if exists (select name from sysobjects where name like 'sp_DanhSachKhachHang')
drop procedure sp_DanhSachKhachHang
go
create proc sp_DanhSachKhachHang
as
set tran isolation level read committed
begin tran
select kh.MaKH,kh.Ten,kh.DiaChi,kh.MaLoaiKH,kh.MaTruSo,kh.SoDT,loai.TenLoai as LoaiKH,ts.Ten as ChiNhanh
from KhachHang kh,LoaiKH loai,TruSo ts
where kh.MaLoaiKH=loai.MaLoai and kh.MaTruSo=ts.MaTruSo
commit tran
go
------------------------- | 11hca1-banking-system | trunk/Database/Procedure_Error/KhachHang.sql | TSQL | asf20 | 1,568 |
------------Tim ma khach hang------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanChinh_GetByMaKH')
drop procedure Proc_TaiKhoanChinh_GetByMaKH
go
create PROC Proc_TaiKhoanChinh_GetByMaKH (@maKH int )
as
select * from TaiKhoanChinh
where MaKH= @maKH
go
---------------------
| 11hca1-banking-system | trunk/Database/Procedure_Error/Thien/Others.sql | TSQL | asf20 | 330 |
------Insert TK tiet kiem-----------
if exists (select name from sysobjects where name like 'Proc_TKTietKiem_Insert')
drop procedure Proc_TKTietKiem_Insert
go
create PROC Proc_TKTietKiem_Insert (@MaTKChinh int, @sotien float,@MaChiTietLS int,@MaLoaiTK int, @ngaygui datetime, @ngaydaohan datetime, @type int)
as
begin
if(@type=1)--dirty
begin
begin tran
insert into TaiKhoanTietKiem(MaTKChinh, SoTien, MaChiTietLS, NgayGui, NgayDaoHan, DelFlg, MaLoaiTK)
values( @MaTKChinh, @sotien, @MaChiTietLS, @ngaygui, @ngaydaohan, 0,@MaLoaiTK)
waitfor delay '00:00:05'
rollback tran
end
if(@type=2)--phantom
begin
begin tran
insert into TaiKhoanTietKiem(MaTKChinh, SoTien, MaChiTietLS, NgayGui, NgayDaoHan, DelFlg, MaLoaiTK)
values( @MaTKChinh, @sotien, @MaChiTietLS, @ngaygui, @ngaydaohan, 0,@MaLoaiTK)
commit tran
end
end
go
-----------update ngay gui va ngay dao han --------------
if exists (select name from sysobjects where name like 'Proc_TKTietKiem_UpdateNgay')
drop procedure Proc_TKTietKiem_UpdateNgay
go
create PROC Proc_TKTietKiem_UpdateNgay (@MaTkTietKiem int, @sotien float, @ngaygui datetime, @ngaydaohan datetime, @type int)
as
begin
if(@type=1)--dirty
begin
begin tran
update TaiKhoanTietKiem set SoTien=@sotien, NgayGui=@ngaygui, NgayDaoHan=@ngaydaohan
where MaTkTietKiem = @MaTkTietKiem
waitfor delay '00:00:05'
rollback tran
end
if(@type=3)--unrepeatable
begin
begin tran
update TaiKhoanTietKiem set SoTien=@sotien, NgayGui=@ngaygui, NgayDaoHan=@ngaydaohan
where MaTkTietKiem = @MaTkTietKiem
commit tran
end
end
go
-----------Rut So Tiet Kiem-------
if exists (select name from sysobjects where name like 'Proc_TKTietKiem_RutSoTK')
drop procedure Proc_TKTietKiem_RutSoTK
go
create PROC Proc_TKTietKiem_RutSoTK (@MaTkTietKiem int,@DelFlg int, @type int)
as
begin
if(@type=1)--dirty
begin
begin tran
update TaiKhoanTietKiem set DelFlg=@DelFlg
where MaTkTietKiem = @MaTkTietKiem
waitfor delay '00:00:05'
rollback tran
end
if(@type=3)--unrepeatable
begin
begin tran
update TaiKhoanTietKiem set DelFlg=@DelFlg
where MaTkTietKiem = @MaTkTietKiem
commit tran
end
end
go
------------------xem thong tin tai khoan tiet kiem qua ma tai khoan chinh ------------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanTietKiem_GetByMaTKChinh')
drop procedure Proc_TaiKhoanTietKiem_GetByMaTKChinh
go
create PROC Proc_TaiKhoanTietKiem_GetByMaTKChinh (@maTKChinh int,@type int)
as
begin
if(@type=1)--dirty
begin
begin tran
set tran isolation level read uncommitted
select * from TaiKhoanTietKiem
where MaTKChinh = @maTKChinh and DelFlg=0
commit tran
end
else if(@type=2)--phantom
begin
begin tran
set transaction isolation level repeatable read
select * from TaiKhoanTietKiem where MaTKChinh = @maTKChinh and DelFlg=0
waitfor delay '00:00:05'
select * from TaiKhoanTietKiem where MaTKChinh = @maTKChinh and DelFlg=0
commit tran
end
else if(@type=3)--unrepeatable
begin
begin tran
waitfor delay '00:00:05'
select * from TaiKhoanTietKiem
where MaTKChinh = @maTKChinh and DelFlg=0
commit tran
end
end
go
--Others
------------------xem Danh Sach Ky Han ------------------
if exists (select name from sysobjects where name like 'Proc_KyHan_All')
drop procedure Proc_KyHan_All
go
create PROC Proc_KyHan_All
as
select * from LoaiKyHanLS
where DelFlg=0
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/Thien/TKTietKiem-error.sql | TSQL | asf20 | 3,539 |
--8.NV duyet lenh chuyen tien ngoai NH, trong khi do KH va xem chi tiet GD
if exists (select name from sysobjects where name like 'Proc_GDNgoaiNH_Update')
drop procedure Proc_GDNgoaiNH_Update
go
create PROC Proc_GDNgoaiNH_Update (@maGD int,@trangthai int,@type int)
as
begin
if(@type=1)--dirty
begin
begin tran
Update GiaoDich
set TrangThaiGD=@trangthai
where MaGD=@maGD
waitfor delay '00:00:05'
rollback tran
end
else if(@type=2)--phantom
begin
select * from GiaoDich
end
else if(@type=3)--unrepeatable
begin
begin tran
Update GiaoDich
set TrangThaiGD=@trangthai
where MaGD=@maGD
commit tran
end
end
go
---------------
if exists (select name from sysobjects where name like 'Proc_AllGD_ByID')
drop proc Proc_AllGD_ByID
go
create proc Proc_AllGD_ByID (@maTKThe int,@type int)
as
begin
if(@type=1)--dirty
begin
begin tran
set tran isolation level read uncommitted
select * from GiaoDich where MaTKThe=@maTKThe
commit tran
end
else if(@type=2)--phantom
begin
begin tran
set tran isolation level repeatable read
select * from GiaoDich where MaTKThe=@maTKThe
waitfor delay '00:00:05'
select * from GiaoDich where MaTKThe=@maTKThe
commit tran
end
else if(@type=3)--unrepeatable
begin
begin tran
--select * from GiaoDich where MaTKThe=@maTKThe
waitfor delay '00:00:05'
select * from GiaoDich where MaTKThe=@maTKThe
commit tran
end
end
go
---------------------------
if exists (select name from sysobjects where name like 'Proc_GiaoDich_ChuyenTienNgoaiNH')
drop procedure Proc_GiaoDich_ChuyenTienNgoaiNH
go
create PROC Proc_GiaoDich_ChuyenTienNgoaiNH (@maTKThe int ,@loaiGD int , @ngayGD datetime ,
@diaChi nvarchar (50), @soTienGD float , @noiDung nvarchar,@MaTKNhan int,@MaNganHang int,@maNV int, @trangThai int,@type int)
as
begin
if(@type=1)--dirty
begin
begin tran
update TaiKhoanThe set SoDu = SoDu-@soTienGD where MaTaiKhoanThe=@maTKThe
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,NoiDungGD, MaTKNhan,MaNganHang,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD , @diaChi , @soTienGD , @noiDung,@MaTKNhan,@MaNganHang, @maNV, @trangThai)
waitfor delay '00:00:05'
rollback tran
end
else if(@type=2)--phantom
begin
begin tran
update TaiKhoanThe set SoDu = SoDu-@soTienGD where MaTaiKhoanThe=@maTKThe
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,NoiDungGD, MaTKNhan,MaNganHang,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD , @diaChi , @soTienGD , @noiDung,@MaTKNhan,@MaNganHang, @maNV, @trangThai)
commit tran
end
end
go
---------------------------
if exists (select name from sysobjects where name like 'Proc_GiaoDich_ChuyenTienTrongNH')
drop procedure Proc_GiaoDich_ChuyenTienTrongNH
go
create PROC Proc_GiaoDich_ChuyenTienTrongNH (@maTKThe int ,@loaiGD int , @ngayGD datetime ,
@diaChi nvarchar (50), @soTienGD float , @noiDung nvarchar,@MaTKNhan int,@maNV int, @trangThai int,@type int)
as
begin
if(@type=1)--dirty
begin
begin tran
update TaiKhoanThe set SoDu = SoDu-@soTienGD where MaTaiKhoanThe=@maTKThe
update TaiKhoanThe set SoDu = SoDu+@soTienGD where MaTaiKhoanThe=@MaTKNhan
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,NoiDungGD,MaTKNhan,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD , @diaChi , @soTienGD, @noiDung,@MaTKNhan,@maNV, @trangThai)
waitfor delay '00:00:05'
rollback tran
end
else if(@type=2)--phantom
begin
begin tran
update TaiKhoanThe set SoDu = SoDu-@soTienGD where MaTaiKhoanThe=@maTKThe
update TaiKhoanThe set SoDu = SoDu+@soTienGD where MaTaiKhoanThe=@MaTKNhan
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,NoiDungGD,MaTKNhan,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD , @diaChi , @soTienGD, @noiDung,@MaTKNhan,@maNV, @trangThai)
commit tran
end
else if(@type=3)--unrepeatable
begin
select * from GiaoDich
end
end
go
--------------
if exists (select name from sysobjects where name like 'Proc_NganHang_GetAll')
drop procedure Proc_NganHang_GetAll
go
create PROC Proc_NganHang_GetAll
as
begin
select * from NganHang where TrangThai=0
end
go
--------
if exists (select name from sysobjects where name like 'Proc_AllGD_ChuyenTienNgoaiNH')
drop procedure Proc_AllGD_ChuyenTienNgoaiNH
go
create PROC Proc_AllGD_ChuyenTienNgoaiNH
as
begin
select * from GiaoDich where TrangThaiGD = -1
end
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/Thien/GiaoDich-error.sql | TSQL | asf20 | 4,559 |
--3.Cap nhat sodu cho TKA,trong khi do KH A kiem tra sodu(TaiKhoanThe)
if exists (select name from sysobjects where name like 'Proc_GiaoDich_RutTien')
drop procedure Proc_GiaoDich_RutTien
go
create PROC Proc_GiaoDich_RutTien (@maTKThe int ,@loaiGD int , @ngayGD datetime ,
@diaChi nvarchar (50), @soTienGD float , @noiDung nvarchar,@maNV int, @trangThai int)
as
begin
insert into GiaoDich(MaTKThe,LoaiGD,NgayGD,DiaChiGD,SoTienGD,NoiDungGD ,MaNVGD,TrangThaiGD)
values (@maTKThe ,@loaiGD , @ngayGD , @diaChi , @soTienGD , @noiDung, @maNV, @trangThai)
end
go
------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_UpdateSodu')
drop procedure Proc_TaiKhoanThe_UpdateSodu
go
create PROC Proc_TaiKhoanThe_UpdateSodu (@maTKThe int,@soDu float, @type int)
as
begin
if(@type=1)--DirtyRead
begin
begin tran
Update TaiKhoanThe
set SoDu= SoDu-@soDu
where MaTaiKhoanThe= @maTKThe
waitfor delay '00:00:5'
rollback tran
end
else if(@type=3)--unrepeatable read
begin
begin tran
Update TaiKhoanThe set SoDu=SoDu-@sodu
where MaTaiKhoanThe=@maTKThe
commit tran
end
end
go
begin tran
Update TaiKhoanThe set SoDu=SoDu + 300
where MaTaiKhoanThe=1
commit tran
-----------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_GetByMaTaiKhoanChinh')
drop procedure Proc_TaiKhoanThe_GetByMaTaiKhoanChinh
go
create PROC Proc_TaiKhoanThe_GetByMaTaiKhoanChinh (@maTK int, @type int)
as
begin
if(@type=1)--Dirty Read
begin
begin tran
set tran isolation level read uncommitted
select * from TaiKhoanThe
where MaTkChinh = @maTK
commit tran
end
else if(@type=2)--phantom
begin
begin tran
set transaction isolation level repeatable read
select * from TaiKhoanThe where MaTkChinh=@maTK
waitfor delay '00:00:10'
select * from TaiKhoanThe where MaTkChinh=@maTK
commit tran
end
else if(@type=3)--Unrepeatable
begin
begin tran
waitfor delay '00:00:10'
select * from TaiKhoanThe where MaTkChinh = @maTK
commit tran
end
end
go
----------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanThe_Insert')
drop procedure Proc_TaiKhoanThe_Insert
go
create PROC Proc_TaiKhoanThe_Insert
(@maTKC int, @sodu float, @laisuat float,@maloaithe int,@maloaitien int, @maloaiTK int, @maKH int,@mapin nchar)
as
declare @maTKThe int
insert into TaiKhoanThe(MaTkChinh,SoDu,LaiSuat,MaLoaiThe,LockFlg,DelFlg,MaLoaiTien,MaLoaiTK)
values(@maTKC, @sodu, @laisuat, @maloaithe, 0, 0, @maloaitien,@maloaiTK)
set @maTKThe = (select top(1)MaTaiKhoanThe from TaiKhoanThe order by MaTaiKhoanThe desc)
insert into ChiTietThe(MaTKThe,MaSoKH,NgayTao,LockFlg,DelFlg,MaSoPin)
values(@maTKThe, @maKH, getdate(), 0, 0,@mapin)
select @maTKThe
go
----------------------
if exists (select name from sysobjects where name like 'Proc_LoaiTaiKhoan_TKThe')
drop procedure Proc_LoaiTaiKhoan_TKThe
go
create PROC Proc_LoaiTaiKhoan_TKThe
as
begin
select * from LoaiTaiKhoan where DelFlg=0 and TKTheFlg=1
end
go
-----------------
if exists (select name from sysobjects where name like 'Proc_TaiKhoanChinh_GetByMaKH')
drop procedure Proc_TaiKhoanChinh_GetByMaKH
go
create PROC Proc_TaiKhoanChinh_GetByMaKH (@maKH int )
as
select * from TaiKhoanChinh
where MaKH= @maKH
go
------------
| 11hca1-banking-system | trunk/Database/Procedure_Error/Thien/TKThe-error.sql | TSQL | asf20 | 3,400 |
if exists (select name from sysobjects where name like 'sp_UpdateMatKhau')
drop procedure sp_UpdateMatKhau
go
create proc sp_UpdateMatKhau(@madangnhap int, @matkhau char)
as
begin
Update TaiKhoanDangNhapNV set MatKhau=@matkhau where MaDangNhap=@madangnhap
end
go
------------------------
if exists (select name from sysobjects where name like 'sp_TaoTKDangNhap')
drop procedure sp_TaoTKDangNhap
go
create proc sp_TaoTKDangNhap(@tendangnhap int, @matkhau char)
as
begin
insert into TaiKhoanDangNhapNV values(@tendangnhap, @matkhau, getdate(),0)
end
go
-------------------------
if exists (select name from sysobjects where name like 'sp_TaoNhanVien')
drop procedure sp_TaoNhanVien
go
create proc sp_TaoNhanVien
(@matruso int,@ten nvarchar(50),@TenDN varchar,@matkhau varchar,@ngaysinh datetime,@diachi nvarchar(50),@dienthoai int,@maGTinh int,@cmnd int,@mota nvarchar(50))
as
begin
declare @maDN int
insert into TaiKhoanDangNhapNV values(@TenDN, @matkhau, getdate(),0)
set @maDN
insert into NhanVien values(@matruso, @ten, @maDN, @ngaysinh, @diachi, @dienthoai, @maGTinh, @cmnd, @mota,0 )
end
go
-----------------
if exists (select name from sysobjects where name like 'sp_GioiTinh')
drop procedure sp_GioiTinh
go
create proc sp_GioiTinh
as
begin
select * from GioiTinh
end
go
-----------------------------
if exists (select name from sysobjects where name like 'sp_GioiTinh_ByID')
drop procedure sp_GioiTinh_ByID
go
create proc sp_GioiTinh_ByID (@ma int)
as
begin
select * from GioiTinh where MaLoaiGioiTinh=@ma
end
go
------------------------
if exists (select name from sysobjects where name like 'sp_DanhSachNhanVien')
drop procedure sp_DanhSachNhanVien
go
create proc sp_DanhSachNhanVien
as
begin
select * from NhanVien
end
go
---------------------
if exists (select name from sysobjects where name like 'sp_DanhSachNhanVien_ByID')
drop procedure sp_DanhSachNhanVien_ByID
go
create proc sp_DanhSachNhanVien_ByID (@maNV int)
as
begin
select * from NhanVien where MaNV=@maNV
end
go
----------------
if exists (select name from sysobjects where name like 'sp_ChucVuActive_View')
drop procedure sp_ChucVuActive_All
go
create proc sp_ChucVuActive_All
as
begin
select * from ChucVu where DelFlag=0
end
go
---------
if exists (select name from sysobjects where name like 'sp_QuyenActive_View')
drop procedure sp_QuyenActive_View
go
create proc sp_QuyenActive_View
as
begin
select * from Quyen where DelFlag=0
end
go
| 11hca1-banking-system | trunk/Database/Procedure_Error/Thien/store_InsertDL.sql | TSQL | asf20 | 2,536 |
-----------------------------------------------------------------------------------------
-- filename : player.lua
-- description : player logic and atributte must be here
-----------------------------------------------------------------------------------------
-- Load needed libraries/scripts
local player = {}
local player_mt = {__index = player}
local pion = require "pion"
local layer = require "layer"
local storyboard = require "storyboard"
local json = require "json"
local fontfactory = require "fontfactory"
-- loacal variables
player.n = 0
players = {}
nMax = 5
function player.new(name)
if(name == nil) then
name = "dummy"
end
-- load description of player based on name character json file
local playerJson = loadJSON("assets/chara/"..name..".json")
local newPlayer = {
id = player.n,
pions = {},
enable = true,
nDiceTurn = 0,
score = 0,
scoreText = nil
}
player.n = player.n + 1
if(newPlayer.id == 0) then
local player_image = display.newImageRect( "assets/chara/"..playerJson.image.image_path,playerJson.image.width, playerJson.image.height, true )
player_image:setReferencePoint(display.TopLeftReferencePoint)
player_image.x = -140
player_image.y = 20
player_image:addEventListener("touch", newPlayer)
player_image:setReferencePoint(display.CenterReferencePoint)
local player_image_back = display.newImageRect( "assets/chara/"..playerJson.image.image_bright,playerJson.image.width, playerJson.image.height, true )
player_image_back:setReferencePoint(display.TopLeftReferencePoint)
player_image_back.x = -140
player_image_back.y = 20
player_image_back:addEventListener("touch", newPlayer)
player_image_back:setReferencePoint(display.CenterReferencePoint)
player_image_back:scale(1.1,1.1)
local image = display.newImageRect( "assets/hud_bar.png", 144, 66, true )
image:setReferencePoint(display.TopLeftReferencePoint)
image.x = 0
image.y = 0 + display.screenOriginY
local switch = display.newImageRect( "assets/switch_on.png", 45, 59, isFullResolution )
switch:setReferencePoint(display.TopLeftReferencePoint)
switch.x = 17
switch.y = 250
local switch_off = display.newImageRect( "assets/switch_off.png", 45, 59, isFullResolution )
switch_off:setReferencePoint(display.TopLeftReferencePoint)
switch_off.x = 17
switch_off.y = 250
--newPlayer:setReferencePoint(display.TopRightReferencePoint)
newPlayer.scoreText = display.newText("0",0,0,fontfactory.dimitry,16)
newPlayer.scoreText.x = image.width - 25
newPlayer.scoreText.y = 15 + display.screenOriginY
layer.insertImage(layer.BACKGROUND,player_image_back)
layer.insertImage(layer.BACKGROUND,player_image)
layer.insertImage(layer.HUD,image)
layer.insertImage(layer.HUD,switch)
layer.insertImage(layer.HUD,switch_off)
newPlayer.image = player_image
newPlayer.effect = player_image_back
newPlayer.switch_on = switch;
newPlayer.switch_off = switch_off;
elseif (newPlayer.id == 1) then
local player_image = display.newImageRect( "assets/chara/"..playerJson.image.image_path,playerJson.image.width, playerJson.image.height, true )
player_image:setReferencePoint(display.TopRightReferencePoint)
player_image.y = 20
player_image.x = 480+140
player_image:addEventListener("touch", newPlayer)
player_image:setReferencePoint(display.CenterReferencePoint)
player_image.xScale = -1
local player_image_back = display.newImageRect( "assets/chara/"..playerJson.image.image_bright,playerJson.image.width, playerJson.image.height, true )
player_image_back:setReferencePoint(display.TopRightReferencePoint)
player_image_back.x = 480+140
player_image_back.y = 20
player_image_back:addEventListener("touch", newPlayer)
player_image_back:setReferencePoint(display.CenterReferencePoint)
player_image_back.xScale = -1
player_image_back:scale(1.1,1.1)
local image = display.newImageRect( "assets/hud_bar.png", 144, 66, true )
image:setReferencePoint(display.TopLeftReferencePoint)
image.xScale = -1
image.x = 480
image.y = 0 + display.screenOriginY
local switch = display.newImageRect( "assets/switch_on.png", 45, 59, isFullResolution )
switch:setReferencePoint(display.TopLeftReferencePoint)
switch.xScale = -1
switch.y = 250
switch.x = 480-17
local switch_off = display.newImageRect( "assets/switch_off.png", 45, 59, isFullResolution )
switch_off:setReferencePoint(display.TopLeftReferencePoint)
switch_off.xScale = -1
switch_off.y = 250
switch_off.x = 480-17
--newPlayer:setReferencePoint(display.TopLeftReferencePoint)
newPlayer.scoreText = display.newText("0",0,0,fontfactory.dimitry,16)
newPlayer.scoreText.x = 480 - image.width + 25
newPlayer.scoreText.y = 15 + display.screenOriginY
layer.insertImage(layer.BACKGROUND,player_image_back)
layer.insertImage(layer.BACKGROUND,player_image)
layer.insertImage(layer.HUD,image)
layer.insertImage(layer.HUD,switch)
layer.insertImage(layer.HUD,switch_off)
newPlayer.image = player_image
newPlayer.effect = player_image_back
newPlayer.switch_on = switch;
newPlayer.switch_off = switch_off;
end
layer.insertImage(layer.HUD, newPlayer.scoreText)
setmetatable(newPlayer,player_mt)
table.insert(players,newPlayer)
return newPlayer
end
function player:touch(event)
if (event.phase == "began") then
local options =
{
effect = "slideRight",
time = 300,
params =
{
callback = self,
playerid = self.id,
character = "assets/chara/character_gameplay_dummy.png"
}
}
if(self.id == 1) then
options.effect = "slideLeft"
end
storyboard.showOverlay("pause_scene",options)
end
return true
end
function player:addPion(_pion)
table.insert(self.pions,_pion)
end
function player:removePion(_pion)
local idx = -1
for i=1,table.getn(self.pions) do
if(self.pions[i] == _pion) then
idx = i
break
end
end
if(idx >= 0) then
table.remove(self.pions,idx)
end
end
function player:createPion(_board,row,col)
local newPion = pion.new(self,_board,row,col)
self:addPion(newPion)
return newPion
end
function player:isFinishTurn()
for i=1,table.getn(self.pions) do
if(self.pions[i].enable) then
return false
end
end
return true
end
function player:remainPions()
local count = 0
for i=1,table.getn(self.pions) do
if(self.pions[i].enable) then
count = count + 1
end
end
return count
end
function player:startTurn()
self.image:setFillColor(255, 255, 255)
self.effect.alpha = 150
self.image.xScale = 1.1
self.image.yScale = 1.1
if(self.id == 1) then
self.image.xScale = self.image.xScale*-1
end
for i=1,table.getn(self.pions) do
self.pions[i]:setEnable(true)
end
-- switch on
self.switch_on.isVisible = true;
self.switch_off.isVisible = false;
end
function player:endTurn()
self.image:setFillColor(100, 100, 100)
self.image.xScale = 0.8
self.image.yScale = 0.8
self.effect.alpha = 0
if(self.id == 1) then
self.image.xScale = self.image.xScale*-1
end
for i=1,table.getn(self.pions) do
self.pions[i].enable = false
end
-- switch off
self.switch_on.isVisible = false;
self.switch_off.isVisible = true;
end
function player:nextTurn(cPlayer)
for i=1,table.getn(players) do
if (players[i].id == cPlayer.id) then
print("AAAAAA")
cPlayer:endTurn()
if(i+1 == table.getn(players)+1) then
players[(1)]:startTurn()
else
players[(i+1)]:startTurn()
end
break
end
end
end
function player:addScore(difScore)
self.score = self.score + difScore
self.scoreText.text = ""..self.score
end
function player:isDiceFull()
return table.getn(self.pions) == nMax
end
function loadJSON( filename )
-- set default base dir if none specified
local base = system.ResourceDirectory
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
--return decoded json string
return json.decode( contents )
else
--or return nil if file didn't ex
return nil
end
end
return player | 0nc0m-3n4k | trunk/player.lua | Lua | mit | 8,608 |
-----------------------------------------------------------------------------------------
-- filename : json.lua
-- description : script to enable load JSON File
-----------------------------------------------------------------------------------------
local json = {}
function json.load( filename )
-- set default base dir if none specified
local base = system.ResourceDirectory
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
--return decoded json string
return json.decode( contents )
else
--or return nil if file didn't ex
return nil
end
end
return json | 0nc0m-3n4k | trunk/json.lua | Lua | mit | 1,007 |
-----------------------------------------------------------------------------------------
-- filename : main.lua
-- description : main.lua is main script for game to run
-----------------------------------------------------------------------------------------
-- Load needed libraries/scripts
local storyboard = require "storyboard"
-- load gamescreen.lua
storyboard.gotoScene("gamescreen") | 0nc0m-3n4k | trunk/main.lua | Lua | mit | 401 |
-----------------------------------------------------------------------------------------
-- filename : tile.lua
-- description : tile object
-----------------------------------------------------------------------------------------
-- load needed libraries/scripts
local layer = require "layer"
-- local variables
local tile = {}
local tile_mt = {__index = tile}
-- STATIC
tile.BLANK = 0
tile.DEATH = 1
tile.PLUS1 = 2
tile.MIN1 = 3
tile.HALF = 4
tile.DOUBLE = 5
tile.BARRED = 6
tile.DIRECTION = 7
tile.MOVEMENT1 = 8
tile.JUMP = 9
tile.REROLL = 10
tile.BEAM = 11
tile.REBIRTH = 12
tile.DIR_UP = 2
tile.DIR_DOWN = 3
tile.DIR_LEFT = 1
tile.DIR_RIGHT = 0
-- PRIVIATE FUNCTION
-- PUBLIC FUNCTION
function tile.new(typeTile,xPos,yPos,width,height,direction)
local newTile = {
tile_type = typeTile,
direction = direction or 0,
image = display.newImageRect( "assets/tile"..typeTile..".png", width, height ),
animation = nil
}
newTile.image:setReferencePoint(display.TopLeftReferencePoint)
newTile.image.x = xPos
newTile.image.y = yPos
newTile.image:setReferencePoint(display.CenterReferencePoint)
if(newTile.direction == tile.DIR_UP) then
newTile.image.rotation = 270
elseif(newTile.direction == tile.DIR_DOWN) then
newTile.image.rotation = 90
elseif(newTile.direction == tile.DIR_LEFT) then
newTile.image.rotation = 180
end
layer.insertImage(layer.BOARD,newTile.image)
return setmetatable(newTile, tile_mt)
end
function tile:playAnim()
if(self.tile_type == tile.BARRED) then
local sheetData = {
width=169,
height=167,
numFrames=4,
sheetContentWidth=169*2,
sheetContentHeight=167*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/barred_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 4,
time = 1000, -- time in millisecond
loopCount = 0,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
animation:play()
self.animation = animation;
layer.insertImage(layer.DIR,animation)
elseif (animation ~= nil) then
self.animation:play()
end
end
function tile:stopAnim()
if(self.animation ~= nil and object.isPlaying == true) then
self.animation:pause()
end
end
return tile | 0nc0m-3n4k | trunk/tile.lua | Lua | mit | 2,423 |
-----------------------------------------------------------------------------------------
-- filename : pion.lua
-- description : Dice script and logic must be here
-----------------------------------------------------------------------------------------
-- load needed libaries/scripts
local layer = require "layer"
local tile = require "tile"
local math = require "math"
local storyboard = require "storyboard"
-- local variables
local pion = {}
local pion_mt = { __index = pion } --metatable
-- global variables
pion.UP = 0
pion.DOWN = 1
pion.LEFT = 2
pion.RIGHT = 3
pion.cPion = nil
local function normalizeScore(score)
if score > 6 then
score = 6
elseif score <= 0 then
score = 1
end
return score
end
-- PUBLIC FUNCTION
function pion.new(player,board, rowPos, colPos)
local newPion = {
board = board or {},
row = rowPos or 1,
col = colPos or 1,
score = 1,
enable = true,
player = player or nil,
image = display.newImageRect( "assets/player-"..player.id.."/pion1.png",43, 51, true ),
isFloat = false
}
layer.insertImageByIndex(layer.PION, newPion.row, newPion.image)
newPion.image:addEventListener("touch", newPion)
setmetatable( newPion, pion_mt )
board:addPion(newPion)
--newPion:commit();
newPion.image:setReferencePoint(display.CenterReferencePoint)
local x = newPion.board.x + (newPion.col-1)*newPion.board.tileWidth + newPion.board.tileWidth/2
local y = newPion.board.y + (newPion.row-1)*newPion.board.tileHeight + newPion.board.tileHeight/2 - 4
local complete = function ( event )
newPion:setFloat(false)
end
transition.to(newPion.image, {time = 650, x = x, y = y, alpha = 1, transition = easing.inOutExpo, onComplete=complete})
return newPion
end
--
function pion:setScore(newScore)
self.score = newScore
self.score = normalizeScore(self.score)
self:setScoreImage()
end
function pion:addScore(difScore)
self.score = self.score + difScore
self.score = normalizeScore(self.score)
end
function pion:mulScore(factor)
if (self.score <= 3) then
self.score = self.score * factor
self.score = normalizeScore(self.score)
end
end
function pion:divScore(factor)
self.score = math.ceil(self.score / factor)
self.score = normalizeScore(self.score)
end
function pion:touch( event )
if (event.phase == "began" and self.enable and self.isFloat == false) then
print(self.isFloat)
if(pion.cPion ~= nil) then
pion.cPion:setFloat(false)
end
layer.clean(layer.DIR)
self:setFloat(true)
pion.cPion = self
local res = false
res = self:addDirectionPointer(0,1) or res
res = self:addDirectionPointer(0,-1) or res
res = self:addDirectionPointer(1,0) or res
res = self:addDirectionPointer(-1,0) or res
print("remain : " .. self.player:remainPions())
if(res == false or self:isMovable() == false) then
self:setFloat(false)
layer.clean(layer.DIR)
if(self.player:remainPions() <= 1) then
self:setEnable(false)
if(self.player:isFinishTurn()) then
local cPlayer = self.player
self.player:nextTurn(cPlayer)
end
end
end
elseif (event.phase == "began") then
if(pion.cPion ~= nil) then
pion.cPion:setFloat(false)
end
layer.clean(layer.DIR)
end
return true
end
function pion:setEnable(enable)
print("enable")
print(enable)
if(enable == self.enable) then
return
end
print("enable continue")
self.enable = enable
-- local x = self.image.x
-- local y = self.image.y
-- self.image.parent:remove(self.image)
-- self.image = nil
-- if(enable == false) then
-- self.image = display.newImageRect( "assets/player-"..self.player.id.."/select/pion".. self.score..".png",43, 43, true );
-- self.image.x = x
-- self.image.y = y
-- x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
-- y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2
-- transition.to(self.image, {time = 700, x = x, y = y, transition = easing.outInExpo, onComplete=complete})
-- else
-- self.image = display.newImageRect( "assets/player-"..self.player.id.."/pion".. self.score..".png",43, 51, true );
-- self.image.x = x
-- self.image.y = y-4
-- x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
-- y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2 - 4
-- transition.to(self.image, {time = 700, x = x, y = y, transition = easing.inOutExpo, onComplete=complete})
-- end
-- layer.insertImageByIndex(layer.PION,self.row,self.image)
-- self.image:addEventListener("touch", self)
end
function pion:isMovable()
return self:checkDirection(-1,0) or self:checkDirection(1,0) or self:checkDirection(0,-1) or self:checkDirection(0,1)
end
function pion:setFloat(_float,complete)
if(_float ~= self.isFloat) then
print("====")
print(_float)
print(self.isFloat)
if(_float) then
local x = self.image.x
local y = self.image.y
self.image.parent:remove(self.image)
self.image = nil
self.image = display.newImageRect( "assets/player-"..self.player.id.."/select/pion".. self.score..".png",43, 43, true );
self.image.x = x
self.image.y = y
x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2
transition.to(self.image, {time = 200, x = x, y = y, transition = easing.outInExpo, onComplete=complete})
elseif (_float ~= true) then
local x = self.image.x
local y = self.image.y
self.image.parent:remove(self.image)
self.image = nil
self.image = display.newImageRect( "assets/player-"..self.player.id.."/pion".. self.score..".png",43, 51, true );
self.image.x = x
self.image.y = y-4
x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2 - 4
transition.to(self.image, {time = 200, x = x, y = y, transition = easing.inOutExpo, onComplete=complete})
end
layer.insertImageByIndex(layer.PION,self.row,self.image)
self.image:addEventListener("touch", self)
self.isFloat = _float
print(self.isFloat)
end
end
function pion:checkDirection(difX, difY)
if(self.col + difX > 0 and self.row + difY > 0 and self.col + difX <= self.board.col and self.row + difY <= self.board.row)then
if(self.board:getTileType(self.row + difY,self.col + difX ) == tile.BARRED) then
self.board:getTile(self.row + difY,self.col + difX):playAnim()
return false
elseif (self.board:getTileType(self.row + difY,self.col + difX ) == tile.JUMP) then
self:addDirectionPointer(difX + difX, difY + difY)
elseif (self.board:getTileType(self.row,self.col) == tile.DIRECTION) then
local tile_temp = self.board:getTile(self.row,self.col )
if (tile.DIR_UP == tile_temp.direction and (difY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (difY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (difX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (difX >= 0)) then
return false
end
elseif (self.board:getTileType(self.row + difY,self.col + difX ) == tile.DIRECTION) then
local tile_temp = self.board:getTile(self.row + difY,self.col + difX )
if (tile.DIR_UP == tile_temp.direction and (difY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (difY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (difX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (difX >= 0)) then
return false
end
end
local otherPion = self.board:getPion(self.row+difY,self.col+difX)
if(otherPion ~= nil and self:canPushDir(otherPion,difX,difY) == false) then
return false
end
return true
end
end
function pion:addDirectionPointer(difX,difY)
if(self:checkDirection(difX,difY))then
local image = nil
local isDifX = 0
local isDifY = 0
if(difX > 0) then
isDifX = 1
elseif (difX < 0 ) then
isDifX = -1
end
if(difY > 0) then
isDifY = 1
elseif(difY < 0) then
isDifY = -1
end
if(self.board:getTileType(self.row + difY,self.col + difX ) == tile.JUMP) then
image = layer.createImage(layer.DIR, "assets/highlight_midle.png", self.board.x + (self.col-1 + difX) * self.board.tileWidth, self.board.y + (self.row-1 + difY) * self.board.tileHeight,45,45)
image:setReferencePoint(display.CenterReferencePoint)
if(difX < 0) then
image.rotation = 180
elseif(difY < 0) then
image.rotation = 270
elseif(difY > 0) then
image.rotation = 90
end
elseif(self.board:getTileType(self.row + difY - 1*isDifY,self.col + difX - 1*isDifX ) == tile.JUMP) then
image = layer.createImage(layer.DIR, "assets/highlight_end.png", self.board.x + (self.col-1 + difX) * self.board.tileWidth, self.board.y + (self.row-1 + difY) * self.board.tileHeight,45,45)
image:setReferencePoint(display.CenterReferencePoint)
if(difX < 0) then
image.rotation = 180
elseif(difY < 0) then
image.rotation = 270
elseif(difY > 0) then
image.rotation = 90
end
else
local decor = layer.createImage(layer.DIR, "assets/highlight_decor.png", self.board.x + (self.col-1) * self.board.tileWidth, self.board.y + (self.row-1) * self.board.tileHeight,45,45)
image = layer.createImage(layer.DIR, "assets/highlight.png", self.board.x + (self.col-1 + difX) * self.board.tileWidth, self.board.y + (self.row-1 + difY) * self.board.tileHeight,45,45)
decor:setReferencePoint(display.CenterReferencePoint)
image:setReferencePoint(display.CenterReferencePoint)
if(difX > 0) then
decor.rotation = 180
image.rotation = 180
elseif(difY > 0) then
decor.rotation = 270
image.rotation = 270
elseif(difY < 0) then
decor.rotation = 90
image.rotation = 90
end
end
image.touch = function (event)
local otherPion = self.board:getPion(self.row+difY,self.col+difX)
if(otherPion ~= nil and self:pushDir(otherPion,difX,difY)) then
print("PUSH")
layer.clean(layer.DIR)
self:setFloat(false)
self.enable = false
return true
elseif (otherPion ~= nil) then
print("Failed to PUSH")
layer.clean(layer.DIR)
self:setFloat(false)
return true
end
print("Next Pion is NIL")
print("difX "..difX)
print("difY "..difY)
print(self.col..","..self.row)
self.col = self.col+difX
self.row = self.row+difY
self:commitAndEffect()
layer.clean(layer.DIR)
if(self.player:isFinishTurn()) then
local cPlayer = self.player
self.player:nextTurn(cPlayer)
end
return true
end
image:addEventListener("touch", image)
else
return false
end
return true
end
function pion:addDirectionPointerAt(row,col)
local otherPion = self.board:getPion(row,col)
if(otherPion ~= nil) then
return
end
local image = layer.createImage(layer.DIR, "assets/highlight_alone.png", self.board.x + (col-1) * self.board.tileWidth, self.board.y + (row-1) * self.board.tileHeight,45,45)
image.touch = function (event)
self.col = col
self.row = row
self:commit()
layer.clean(layer.DIR)
layer.insertImageByIndex(layer.PION, self.row, self.image)
self:setEnable(false)
if(self.player:isFinishTurn()) then
local cPlayer = self.player
self.player:nextTurn(cPlayer)
end
end
image:addEventListener("touch", image)
end
function pion:addBeamPointerAt(row,col)
local otherPion = self.board:getPion(row,col)
if(otherPion ~= nil) then
return
end
local sheetData = {
width=self.board.tileWidth,
height=self.board.tileHeight,
numFrames=4,
sheetContentWidth=self.board.tileWidth*4,
sheetContentHeight=self.board.tileHeight*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/beam_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 4,
time = 1000, -- time in millisecond
loopCount = 0,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation:setReferencePoint(display.TopLeftReferencePoint)
animation.x = self.board.x + (col-1) * self.board.tileWidth
animation.y = self.board.y + (row-1) * self.board.tileHeight
animation:setReferencePoint(display.CenterReferencePoint)
animation:play()
layer.insertImage(layer.DIR,animation)
local image = animation
image.touch = function (event)
transition.to(self.image, {time = 650, y = self.image.y-10, alpha = 0, transition = easing.inOutExpo})
self.col = col
self.row = row
-- beam Animation
local sheetData = {
width=169,
height=167,
numFrames=5,
sheetContentWidth=169*3,
sheetContentHeight=167*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/beam_move_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 4,
time = 1000, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation:setReferencePoint(display.CenterReferencePoint)
animation.x = image.x
animation.y = image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
self.image:setReferencePoint(display.CenterReferencePoint)
print(self.col..","..self.row)
local x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
local y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2 - 4
self.image.x = x
self.image.y = y - 20
self:commit()
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
-- end
layer.clean(layer.DIR)
layer.insertImageByIndex(layer.PION, self.row, self.image)
self:setEnable(false)
if(self.player:isFinishTurn()) then
local cPlayer = self.player
self.player:nextTurn(cPlayer)
end
end
image:addEventListener("touch", image)
end
function pion:setEffect(tileType)
local dead = false
if(tileType == tile.PLUS1) then
local sheetData = {
width=169,
height=166,
numFrames=6,
sheetContentWidth=169*3,
sheetContentHeight=166*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/plus_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 6,
time = 800, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
self:addScore(1)
self:setScoreImage()
self.player:addScore(tile.PLUS1)
self:setFloat(false)
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
elseif (tileType == tile.MIN1 and self.score > 0) then
local sheetData = {
width=169,
height=166,
numFrames=6,
sheetContentWidth=169*3,
sheetContentHeight=166*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/minus_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 6,
time = 800, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
self:addScore(-1)
self:setScoreImage()
self.player:addScore(tile.MIN1)
self:setFloat(false)
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
elseif (tileType == tile.HALF) then
local sheetData = {
width=169,
height=166,
numFrames=6,
sheetContentWidth=169*3,
sheetContentHeight=166*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/half_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 6,
time = 800, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
self:divScore(2)
self:setScoreImage()
self.player:addScore(tile.HALF)
self:setFloat(false)
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
elseif (tileType == tile.DOUBLE) then
local sheetData = {
width=169,
height=166,
numFrames=6,
sheetContentWidth=169*3,
sheetContentHeight=166*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/double_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 6,
time = 800, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
self:mulScore(2)
self:setScoreImage()
self.player:addScore(tile.DOUBLE)
self:setFloat(false)
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
elseif (tileType == tile.DEATH) then
print("dead")
dead = true
self.player:addScore(tile.DEATH)
self:commit()
local deadDelay = function (event)
-- Death Animation
local sheetData = {
width=169,
height=167,
numFrames=6,
sheetContentWidth=169*3,
sheetContentHeight=167*2
}
local mySheet = graphics.newImageSheet("assets/tile_animation/death_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
start = 1,
count = 6,
time = 800, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = self.image.x
animation.y = self.image.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
end
end
animation:addEventListener("sprite", animationEnded)
self:dead()
animation:play()
end
timer.performWithDelay( 800, deadDelay )
elseif (tileType == tile.BEAM) then
self:setFloat(false)
self.player:addScore(tile.BEAM)
local options =
{
params =
{
callback = self,
text = "Do you want to activate BEAM ?",
isModal = true
}
}
storyboard.showOverlay("messagebox_scene",options)
elseif (tileType == tile.MOVEMENT1) then
self:setFloat(false)
self.player:addScore(tile.MOVEMENT1)
local options =
{
params =
{
callback = self,
text = "Do you want to activate MOVEMENT1 ?"
}
}
storyboard.showOverlay("messagebox_scene",options)
elseif (tileType == tile.REROLL) then
self:setFloat(false)
self.player:addScore(tile.REROLL)
local options =
{
params =
{
callback = self,
text = "Do you want to activate REROLL ?"
}
}
storyboard.showOverlay("messagebox_scene",options)
elseif (tileType == tile.REBIRTH) then
self:setFloat(false)
self.player:addScore(tile.REBIRTH)
local options =
{
params =
{
callback = self,
text = "Do you want to activate REBIRTH ?"
}
}
storyboard.showOverlay("messagebox_scene",options)
else
self:setFloat(false)
end
if(dead == false) then
layer.insertImageByIndex(layer.PION, self.row, self.image)
end
end
function pion:callbackListen(event)
if(event.result == 1 and self.board:getTileType(self.row,self.col) == tile.MOVEMENT1) then
self:addDirectionPointer(0,1)
self:addDirectionPointer(0,-1)
self:addDirectionPointer(1,0)
self:addDirectionPointer(-1,0)
elseif (event.result == 1 and self.board:getTileType(self.row,self.col) == tile.BEAM) then
self:beamEffect()
elseif (event.result == 1 and self.board:getTileType(self.row,self.col) == tile.REROLL) then
if(event.resultRoll == nil) then
self.player:addScore(tile.REROLL)
local options =
{
params =
{
callback = self,
playerid = self.player.id,
text = "ROLL"
}
}
storyboard.showOverlay("roll_box",options)
else
self:setScore(event.resultRoll)
end
elseif (event.result == 1 and self.board:getTileType(self.row,self.col) == tile.REBIRTH) then
if(event.resultRoll == nil) then
self.player:addScore(tile.REROLL)
local options =
{
params =
{
callback = self,
playerid = self.player.id,
text = "ROLL"
}
}
storyboard.showOverlay("roll_box",options)
else
self:setScore(event.resultRoll)
if(event.resultRoll == 1) then
-- REBIRTH one DICE
end
end
end
layer.insertImageByIndex(layer.PION, self.row, self.image)
end
function pion:beamEffect()
for i=1, self.board.row do
for j=1, self.board.col do
if(self.board:getTileType(i,j) == tile.BEAM) then
self:addBeamPointerAt(i,j)
end
end
end
end
function pion:setEffectPos()
print(self.row .. "," .. self.col..":"..self.board.map[self.row][self.col].tile_type);
self:setEffect(self.board.map[self.row][self.col].tile_type)
end
function pion:setScoreImage()
local x = self.image.x
local y = self.image.y
self.image.parent:remove(self.image)
self.image = nil
if(self.isFloat) then
self.image = display.newImageRect( "assets/player-"..self.player.id.."/select/pion".. self.score..".png",43, 51, true );
else
self.image = display.newImageRect( "assets/player-"..self.player.id.."/pion".. self.score..".png",43, 51, true );
end
self.image.x = x
self.image.y = y
self:commit()
layer.insertImageByIndex(layer.PION,self.row,self.image)
self.image:addEventListener("touch", self)
layer.clean(layer.DIR)
end
function pion:push(_pion)
if(_pion == nil) then
return false
end
local dirX = self.col - pion.col
local dirY = self.row - pion.row
return true
end
function pion:pushDir(_pion,dirX,dirY)
if(self.player.id == _pion.player.id) then
if(_pion:pushNextScore(self.score+_pion.score,dirX,dirY) == false) then
return false
end
else
if(self.score < _pion.score) then return false end
if(_pion:pushMinScore(self.score-_pion.score,dirX,dirY) == false) then
return false
end
end
if(_pion == nil) then
print("Because Next Is NIL")
return false
end
local isDead = false
if(_pion.row + dirY < 1 or _pion.row + dirY > self.board.row or _pion.col + dirX < 1 or _pion.col + dirX > self.board.col) then
isDead = true
end
_pion.row = _pion.row + dirY
_pion.col = _pion.col + dirX
self.row = self.row + dirY
self.col = self.col + dirX
if(isDead) then
_pion:dead()
else
_pion:setEffectPos()
if(_pion.image ~= nil) then
_pion:commit()
end
end
self:setEffectPos()
self:commit()
return true
end
function pion:canPushDir(_pion,dirX,dirY)
if(self.player.id == _pion.player.id) then
if(_pion:canPushNextScore(self.score+_pion.score,dirX,dirY) == false) then
return false
end
else
if(self.score < _pion.score) then return false end
if(_pion:canPushMinScore(self.score-_pion.score,dirX,dirY) == false) then
return false
end
end
if(_pion == nil) then
print("Because Next Is NIL")
return false
end
return true
end
function pion:canPushNextScore(score,dirX,dirY)
print("Push Next Score")
if(self.row + dirY < 1 or self.row + dirY > self.board.row or self.col + dirX < 1 or self.col + dirX > self.board.col) then
return false
end
local tile_type = self.board:getTileType(self.row+dirY,self.col+dirX);
if(tile_type == tile.BARRED) then
return false
elseif (tile_type == tile.DIRECTION) then
local tile_temp = self.board:getTile(self.row + dirY,self.col + dirX )
if (tile.DIR_UP == tile_temp.direction and (dirY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (dirY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (dirX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (dirX >= 0)) then
return false
end
end
local _pion = self.board:getPion(self.row+dirY,self.col+dirX);
if(_pion == nil) then
return false
end
if(self.player.id == _pion.player.id) then
if(_pion:canPushNextScore(score+_pion.score,dirX,dirY) == false) then
return false
end
else
if(score < _pion.score) then return false end
if(_pion:canPushMinScore(score-_pion.score,dirX,dirY) == false) then
return false
end
end
return true
end
function pion:pushNextScore(score,dirX,dirY)
print("Push Next Score")
if(self.row + dirY < 1 or self.row + dirY > self.board.row or self.col + dirX < 1 or self.col + dirX > self.board.col) then
return false
end
local tile_type = self.board:getTileType(self.row+dirY,self.col+dirX);
if(tile_type == tile.BARRED) then
return false
elseif (tile_type == tile.DIRECTION) then
local tile_temp = self.board:getTile(self.row + dirY,self.col + dirX )
if (tile.DIR_UP == tile_temp.direction and (dirY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (dirY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (dirX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (dirX >= 0)) then
return false
end
end
local _pion = self.board:getPion(self.row+dirY,self.col+dirX);
if(_pion == nil) then
return false
end
if(self.player.id == _pion.player.id) then
if(_pion:pushNextScore(score+_pion.score,dirX,dirY) == false) then
return false
end
else
if(score < _pion.score) then return false end
if(_pion:pushMinScore(score-_pion.score,dirX,dirY) == false) then
return false
end
end
local isDead = false
if(_pion.row + dirY < 1 or _pion.row + dirY > self.board.row or _pion.col + dirX < 1 or _pion.col + dirX > self.board.col) then
isDead = true
end
_pion.row = _pion.row + dirY
_pion.col = _pion.col + dirX
if(isDead) then
_pion:dead()
else
_pion:setEffectPos()
if(_pion.image ~= nil) then
_pion:commit()
end
end
return true
end
function pion:canPushMinScore(score,dirX,dirY)
if(self.row + dirY < 1 or self.row + dirY > self.board.row or self.col + dirX < 1 or self.col + dirX > self.board.col) then
return true
end
local tile_type = self.board:getTileType(self.row+dirY,self.col+dirX);
if(tile_type == tile.BARRED) then
print("Push Min Score Failed because Tile is BARRED")
return false
elseif (tile_type == tile.DIRECTION) then
print("Push Min Score Failed because Tile is DIRECTION")
local tile_temp = self.board:getTile(self.row + dirY,self.col + dirX )
if (tile.DIR_UP == tile_temp.direction and (dirY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (dirY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (dirX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (dirX >= 0)) then
return false
end
end
local _pion = self.board:getPion(self.row+dirY,self.col+dirX);
if(_pion == nil) then
return true
end
if(score < _pion.score) then
return false
end
if(_pion:canPushMinScore(score-_pion.score,dirX,dirY) == false) then
return false
end
return true
end
function pion:pushMinScore(score,dirX,dirY)
if(self.row + dirY < 1 or self.row + dirY > self.board.row or self.col + dirX < 1 or self.col + dirX > self.board.col) then
return true
end
local tile_type = self.board:getTileType(self.row+dirY,self.col+dirX);
if(tile_type == tile.BARRED) then
print("Push Min Score Failed because Tile is BARRED")
return false
elseif (tile_type == tile.DIRECTION) then
print("Push Min Score Failed because Tile is DIRECTION")
local tile_temp = self.board:getTile(self.row + dirY,self.col + dirX )
if (tile.DIR_UP == tile_temp.direction and (dirY >= 0)) then
return false
elseif (tile.DIR_DOWN == tile_temp.direction and (dirY <= 0)) then
return false
elseif (tile.DIR_RIGHT == tile_temp.direction and (dirX <= 0)) then
return false
elseif (tile.DIR_LEFT == tile_temp.direction and (dirX >= 0)) then
return false
end
end
local _pion = self.board:getPion(self.row+dirY,self.col+dirX);
if(_pion == nil) then
return true
end
if(score < _pion.score) then
return false
end
if(_pion:pushMinScore(score-_pion.score,dirX,dirY) == false) then
return false
end
local isDead = false
if(_pion.row + dirY < 1 or _pion.row + dirY > self.board.row or _pion.col + dirX < 1 or _pion.col + dirX > self.board.col) then
isDead = true
end
_pion.row = _pion.row + dirY
_pion.col = _pion.col + dirX
if(isDead) then
_pion:dead()
else
_pion:commit()
_pion:setEffectPos()
end
return true
end
function pion:pushNext(dirX,dirY)
end
function pion:commit()
self.image:setReferencePoint(display.CenterReferencePoint)
print(self.col..","..self.row)
local x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
local y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2 - 4
local complete = function ( event )
self:setFloat(false)
end
transition.to(self.image, {time = 650, x = x, y = y, alpha = 1, transition = easing.inOutExpo, onComplete=complete})
end
function pion:commitAndEffect()
self.image:setReferencePoint(display.CenterReferencePoint)
print("Commit And Effect")
local x = self.board.x + (self.col-1)*self.board.tileWidth + self.board.tileWidth/2
local y = self.board.y + (self.row-1)*self.board.tileHeight + self.board.tileHeight/2 - 4
--local complete = function ( event )
local complete = function(event)
self:setEffectPos()
end
-- Adding
--self:setFloat(false,complete2)
-- end of adding
--end
transition.to(self.image, {time = 650, x = x, y = y, transition = easing.inOutExpo, onComplete=complete})
end
function pion:dead()
if(pion.cPion == self) then
pion.cPion = nil
end
self.image.parent:remove(self.image)
self.image = nil
self.board:removePion(self)
self.player:removePion(self)
self = nil
-- remove from player
end
return pion | 0nc0m-3n4k | trunk/pion.lua | Lua | mit | 32,412 |
-----------------------------------------------------------------------------------------
-- filename : layer.lua
-- description : Layering script for game screen
-----------------------------------------------------------------------------------------
-- local variables
local layer = {}
layer.layerTable = {}
layer.BACKGROUND = 0
layer.BOARD = 1
layer.DIR = 2
layer.PION = 3
layer.PION_1 = 0
layer.PION_2 = 1
layer.PION_3 = 2
layer.PION_4 = 3
layer.PION_5 = 4
layer.PION_6 = 5
layer.PION_7 = 6
layer.HUD = 13
layer.CONF = 14
function layer.generateLayerGroup( group, indexNumber)
for i = 0, indexNumber-1 do
layer.layerTable[i] = display.newGroup()
group:insert(layer.layerTable[i])
print("Layer")
end
end
function layer.generateLayer( indexNumber )
for i = 0, indexNumber-1 do
layer.layerTable[i] = display.newGroup()
print("Layer")
end
end
function layer.insertImage(indexLayer,image)
layer.layerTable[indexLayer]:insert(image)
end
function layer.insertImageByIndex(indexLayer, index ,image)
print("layer : "..indexLayer+index)
layer.layerTable[indexLayer+index]:insert(image)
end
function layer.createImage( indexLayer,imageName,left,top,width,height )
local img = display.newImageRect( layer.layerTable[indexLayer], imageName, width, height, true )
img:setReferencePoint(display.TopLeftReferencePoint)
img.x = left
img.y = top
return img
end
function layer.clean(indexLayer)
print(layer.layerTable[indexLayer].numChildren)
for i=layer.layerTable[indexLayer].numChildren,1,-1 do
layer.layerTable[indexLayer][i].parent:remove(layer.layerTable[indexLayer][i])
end
print(layer.layerTable[indexLayer].numChildren)
end
--layer.generateLayer(6)
return layer | 0nc0m-3n4k | trunk/layer.lua | Lua | mit | 1,758 |
-----------------------------------------------------------------------------------------
-- filename : fontfactory.lua
-- description : script to load font and use it on another script
-----------------------------------------------------------------------------------------
-- local variables
local fontfactory = {}
fontfactory.dimitry = "Dimitri"
fontfactory.helveticaBQ = nil
local function init()
print("Init Font factory")
if "Win" == system.getInfo( "platformName" ) then -- for windows platform
fontfactory.dimitry = "Dimitri"
fontfactory.helveticaBQ = "Helvetica BQ"
elseif "Android" == system.getInfo( "platformName" ) then -- for Android
fontfactory.dimitry = "assets/font/DIMITRI"
fontfactory.helveticaBQ = "assets/font/HelveticaBQ-Roman"
else
-- Mac and iOS
fontfactory.dimitry = "Dimitri"
fontfactory.helveticaBQ = "Helvetica BQ"
end
end
init()
return fontfactory | 0nc0m-3n4k | trunk/fontfactory.lua | Lua | mit | 949 |
-----------------------------------------------------------------------------------------
-- filename : button.lua
-- description : script that ease to make a button and button animation
-----------------------------------------------------------------------------------------
-- Load needed libaries/scripte
local fontfactory = require "fontfactory"
-- local variable
local button = {}
-- Create a simple button with no animation
function button.createButton(scene,name,x,y,func)
local group = scene.view
local bg = display.newImageRect( group,"assets/pause/base_btn.png", 133, 30 )
bg:setReferencePoint(display.TopLeftReferencePoint)
bg.x = x
bg.y = y
local btn_text = display.newText(group,name,x,y,fontfactory.dimitry,15)
btn_text:setReferencePoint(display.CenterReferencePoint)
btn_text.x = x + bg.width/2;
btn_text.y = y + bg.height/2;
if(func ~= nil) then
bg:addEventListener("touch", func)
end
end
-- Create a simple button with scale animation
function button.createButtonScaleAnim(scene,name,x,y,func,scale)
local group = scene.view
local bg = display.newImageRect( group,"assets/pause/base_btn.png", 133, 30 )
bg:setReferencePoint(display.TopLeftReferencePoint)
bg.x = x
bg.y = y
local btn_text = display.newText(group,name,x,y,fontfactory.dimitry,15)
btn_text:setReferencePoint(display.CenterReferencePoint)
btn_text.x = x + bg.width/2;
btn_text.y = y + bg.height/2;
bg:setReferencePoint( display.CenterReferencePoint )
local touch = function(event)
if ( event.phase == "began" ) then
bg:scale(scale,scale)
btn_text:scale(scale,scale)
elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
bg:scale(1,1)
btn_text:scale(1,1)
if(func ~= nil) then
func(event)
end
end
return true
end
bg:addEventListener("touch", touch)
end
-- Create a simple button with alpha animation
function button.createButtonAlphaAnim(scene,name,x,y,func,alpha)
local group = scene.view
local bg = display.newImageRect( group,"assets/pause/base_btn.png", 133, 30 )
bg:setReferencePoint(display.TopLeftReferencePoint)
bg.x = x
bg.y = y
local btn_text = display.newText(group,name,x,y,fontfactory.dimitry,15)
btn_text:setReferencePoint(display.CenterReferencePoint)
btn_text.x = x + bg.width/2;
btn_text.y = y + bg.height/2;
bg:setReferencePoint( display.CenterReferencePoint )
local touch = function(event)
if ( event.phase == "began" ) then
bg.alpha = alpha
btn_text.alpha = alpha
elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
bg.alpha = 1
btn_text.alpha = 1
if(func ~= nil) then
func(event)
end
end
return true
end
bg:addEventListener("touch", touch)
end
return button | 0nc0m-3n4k | trunk/button.lua | Lua | mit | 2,862 |
-----------------------------------------------------------------------------------------
-- filename : messagebox_scene.lua
-- description : Simple message box, showing text and yes/no button
-----------------------------------------------------------------------------------------
-- Load needed libraries/scripts
local callback = nil
local storyboard = require "storyboard"
local scene = storyboard.newScene()
local layer = require "layer"
function scene:createScene(event)
print("overlay")
callback = event.params.callback
local group = self.view
local back = display.newRect( group, display.screenOriginX, display.screenOriginY, display.actualContentWidth, display.actualContentHeight )
back:setFillColor(0, 0, 0, 1.0)
back:addEventListener("touch", castRay)
back:addEventListener("tap", castRay)
local background = display.newImageRect( "assets/confirmation/background.png",480,200)
background.x = 480/2
background.y = 320/2
-- Button
local yesImage = display.newImageRect( "assets/confirmation/yes.png", 200, 100 )
yesImage.x = 480/2 -100
yesImage.y = 320/2
yesImage:addEventListener("touch", yes)
local noImage = display.newImageRect( "assets/confirmation/no.png", 200, 100 )
noImage.x = 480/2 + 100
noImage.y = 320/2
noImage:addEventListener("touch", no)
local textConf = display.newText(event.params.text or "", 480/2, 320/2-100, native.systemFontBold, 24)
textConf:setTextColor( 0, 0, 0 )
textConf.x = 480/2
group:insert(background)
group:insert(yesImage)
group:insert(noImage)
group:insert(textConf)
end
function castRay( event )
print("Hello Cast")
return true
end
function yes( event )
if(event.phase == "began") then
print("yes")
if(callback ~= nil) then
local newEvent = {
result = 1
}
storyboard.hideOverlay()
callback:callbackListen(newEvent)
end
end
return true
end
function no( event )
if(event.phase == "began") then
print("yes")
if(callback ~= nil) then
local newEvent = {
result = 0
}
callback:callbackListen(newEvent)
end
storyboard.hideOverlay("fade",800)
end
return true
end
-- add event listener
scene:addEventListener("createScene", scene)
return scene | 0nc0m-3n4k | trunk/messagebox_scene.lua | Lua | mit | 2,257 |
-- BaseScreen.lua
module("BaseScreen",package.seeall)
-- public
imageTable = {}
function Load()
print("test")
end
function UnLoad()
if(imageTable ~= nil) then
imageTable:removeSelf()
end
end | 0nc0m-3n4k | trunk/BaseScreen.lua | Lua | mit | 213 |
----
-- filename : gamescreen.lua
-- description : gamescreen.lua is script for logic in game screen
----
-- Load needed library/script
local storyboard = require "storyboard"
local player = require "player"
local board = require "board"
local layer = require "layer"
local pion = require "pion"
local scene = storyboard.newScene()
-- Local variable
local player0,player1,board1
function scene:createScene(event)
print( "Create Game Scene" )
-- generate layer number
layer.generateLayerGroup(self.view,14)
local xboard = (479-43*7)/2;
local yboard = (340-30-43*7)+7;
-- background image
local back = display.newImageRect( "assets/bg.png",480, 360, true)
back.x = 240
back.y = 160
layer.insertImage(layer.BACKGROUND, back)
-- create 2 new players
player0 = player.new() -- default character
player1 = player.new("rick") -- 'rick' character
-- load board from json file
board1 = board.new(xboard,yboard,43,43,"levels/dummy.json")
-- generate dices for player 0
player0:createPion(board1,2,1)
player0:createPion(board1,3,1)
player0:createPion(board1,4,1)
player0:createPion(board1,5,1)
player0:createPion(board1,6,1)
player0:startTurn() -- start first
-- generate dices for player 1
player1:createPion(board1,2,7)
player1:createPion(board1,3,7)
player1:createPion(board1,4,7)
player1:createPion(board1,5,7)
player1:createPion(board1,6,7)
player1:endTurn()
-- load HUD
local hud_base_title = display.newImageRect( "assets/hud_base_title.png",197, 27 , true )
hud_base_title.x = (480)/2;
hud_base_title.y = 18+display.screenOriginY-3;
local hud_versus_title = display.newImageRect( "assets/hud_versus_title.png",85, 23, true )
hud_versus_title.x = (480)/2;
hud_versus_title.y = 18+display.screenOriginY-3;
-- add HUD to layer HUD
layer.insertImage(layer.HUD, hud_base_title);
layer.insertImage(layer.HUD, hud_versus_title);
end
-- touch logic
function scene:touch( event )
if (event.phase == "began") then
if(pion.cPion ~= nil) then
pion.cPion:setFloat(false)
end
layer.clean(layer.DIR)
end
return true
end
-- add event listener
Runtime:addEventListener("touch", scene)
scene:addEventListener("createScene", scene)
return scene | 0nc0m-3n4k | trunk/gamescreen.lua | Lua | mit | 2,277 |
-----------------------------------------------------------------------------------------
-- filename : roll_box.lua
-- description : messgaebox for showing option wheter player want roll effect or not
-----------------------------------------------------------------------------------------
--load needed libaries/scripts
local storyboard = require "storyboard"
local layer = require "layer"
-- local variables
local callback = nil
local scene = storyboard.newScene()
local playerid = 0
local diceImage = nil
local number = 0
local group = nil
function scene:createScene(event)
print("overlay")
callback = event.params.callback
playerid = event.params.playerid
group = self.view
local background = display.newImageRect( "assets/confirmation/background.png",480,240)
background.x = 480/2
background.y = 320/2
-- header image
local header = display.newImageRect("assets/confirmation/reroll_header.png",480,30)
header.x = 480/2
header.y = 320/2 - 50
-- DiceImage
diceImage = display.newImageRect( "assets/player-"..playerid.."/pion1.png", 63, 76 )
diceImage.x = 480/2
diceImage.y = 320/2 + 20
diceImage:addEventListener("touch", diceTouch)
group:insert(background)
group:insert(header)
group:insert(diceImage)
end
function diceTouch( event )
if(event.phase == "began") then
print("yes")
if(number == 0) then
number = math.random(6)
print("number : "..number)
-- animation dice
-- animation roll
-- WARNING : It's big size image file
local sheetData = {
width=480,
height=100,
numFrames=22,
sheetContentWidth=480*3,
sheetContentHeight=100*8
}
local mySheet = graphics.newImageSheet("assets/animation/reroll_sheet.png",sheetData)
local sequenceData = {
{
name = "animation",
frames = {1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,11,12,13,14,15,16,17,18,19,20,21,22,22,22,22},
time = 3000, -- time in millisecond
loopCount = 1,
loopDirection = "forward"
}
}
local animation = display.newSprite(mySheet, sequenceData)
animation.x = diceImage.x
animation.y = diceImage.y
local animationEnded = function ( event )
if ( event.phase == "ended" ) then
local thisSprite = event.target --"event.target" references the sprite
thisSprite.parent:remove(thisSprite)
elseif(event.phase == "next") then
if(animation.frame == 7) then
local toRightComplete = function (event)
local toLeftComplete = function(event)
diceImage.parent:remove(diceImage)
diceImage = nil
end
transition.to(diceImage, {time = 300, x = diceImage.x - 300, y = diceImage.y, alpha = 1, transition = easing.inOutExpo, onComplete=toLeftComplete})
end
transition.to(diceImage, {time = 200, x = diceImage.x + 100, y = diceImage.y, transition = easing.inOutExpo, onComplete=toRightComplete})
elseif(animation.frame == 32) then
local newDiceImage = display.newImageRect( "assets/player-"..playerid.."/pion"..number..".png", 63, 76 )
newDiceImage.x = 480/2 + 100
newDiceImage.y = 320/2 + 20
newDiceImage:addEventListener("touch", diceTouch)
transition.to(newDiceImage, {time = 300, x = newDiceImage.x - 100, y = newDiceImage.y, transition = easing.inOutExpo, onComplete=toRightComplete})
group:insert(newDiceImage)
end
end
end
animation:addEventListener("sprite", animationEnded)
animation:play()
return true
end
if(callback ~= nil) then
local newEvent = {
result = 1,
resultRoll = number
}
callback:callbackListen(newEvent)
end
storyboard.hideOverlay()
end
return true
end
-- add event listener
scene:addEventListener("createScene", scene)
return scene | 0nc0m-3n4k | trunk/roll_box.lua | Lua | mit | 3,872 |
-----------------------------------------------------------------------------------------
-- filename : pause_scene.lua
-- description : pause scene. All logic for pause in here
-----------------------------------------------------------------------------------------
-- Load needed libraries/scripts
local storyboard = require "storyboard"
local fontfactory = require "fontfactory"
local scene = storyboard.newScene()
local callback = nil
local storyboard = require "storyboard"
local button = require "button"
function scene:createScene(event)
print("Pause Scene")
callback = event.params.callback
self._playerid = event.params.playerid
local img_char = event.params.character
local group = self.view
local back = display.newRect( group, 0, 0, display.actualContentWidth,display.actualContentHeight )
back:setFillColor(0, 0, 0, 1.0)
back:addEventListener("touch", castRay)
back:addEventListener("tap", castRay)
local bg = display.newImageRect( group,"assets/pause/base_pause.png", 382, 313 )
local player_text = display.newText(group,"Player "..(self._playerid+1), 212 + display.screenOriginX, 100, fontfactory.dimitry, 20)
local pause_text = display.newText(group,"Pause Menu", 212 + display.screenOriginX, 118, fontfactory.dimitry, 20)
local image_char = nil
if(img_char ~= nil) then
image_char = display.newImageRect( group,img_char, 200, 200 )
image_char.x = 95 + display.screenOriginX
image_char.y = 155
image_char.xScale = 0.8
image_char.yScale = 0.8
end
player_text:setTextColor(207, 223, 222)
pause_text:setTextColor(207, 223, 222)
bg:setReferencePoint(display.TopLeftReferencePoint)
if(self._playerid == 0) then -- pause scene for left player
bg.y = 30
bg.x = -20 + display.screenOriginX
button.createButtonAlphaAnim(self,"RESUME",200 + display.screenOriginX,150,resume,0.7)
button.createButtonAlphaAnim(self,"QUIT",200 + display.screenOriginX,180,nil,0.7)
button.createButtonAlphaAnim(self,"HELP",200 + display.screenOriginX,210,nil,0.7)
button.createButtonAlphaAnim(self,"MAIN MENU",200 + display.screenOriginX,240,nil,0.7)
else -- pause scene for right player
bg.xScale = -1
bg.y = 30
bg.x = 500 - display.screenOriginX
player_text.x = 225 - display.screenOriginX
pause_text.x = 213 - display.screenOriginX
button.createButtonAlphaAnim(self,"RESUME",149 - display.screenOriginX,150,resume,0.7)
button.createButtonAlphaAnim(self,"QUIT",149 - display.screenOriginX,180,nil,0.7)
button.createButtonAlphaAnim(self,"HELP",149 - display.screenOriginX,210,nil,0.7)
button.createButtonAlphaAnim(self,"MAIN MENU",149 - display.screenOriginX,240,nil,0.7)
if(image_char ~= nil) then
image_char.x = 385 - display.screenOriginX
image_char.y = 155
image_char.xScale = -0.8
image_char.yScale = 0.8
end
end
end
function castRay( event )
return true
end
function resume( event )
print("resume")
storyboard.hideOverlay()
return true
end
-- add event listener
scene:addEventListener("createScene", scene)
return scene | 0nc0m-3n4k | trunk/pause_scene.lua | Lua | mit | 3,083 |
application = {
content = {
graphicsCompatibility = 1, -- Turn on V1 Compatibility Mode
width = 320,
height = 480,
scale = "letterbox",
fps = 60,
imageSuffix = {
["@2x"] = 2,
}
},
orientation =
{
default = "landscapeRight",
supported = { "landscapeLeft", "landscapeRight" },
},
--[[
-- Push notifications
notification =
{
iphone =
{
types =
{
"badge", "sound", "alert", "newsstand"
}
}
}
--]]
}
| 0nc0m-3n4k | trunk/config.lua | Lua | mit | 609 |
-----------------------------------------------------------------------------------------
-- filename : board.lua
-- description : board object
-----------------------------------------------------------------------------------------
-- load needed libraries/scripts
local tile = require "tile"
local json = require "json"
local layer = require "layer"
--local variables
local board = {}
local board_mt = {__index = board}
function board.new(xPos,yPos,tileWidth,tileHeight,col,row)
local newBoard = {
x = xPos,
y = yPos,
tileWidth = tileWidth or 32,
tileHeight = tileHeight or 32,
col = tonumber(col) or 7,
row = tonumber(row) or 7,
pions = {}
}
newBoard.map = {}
for i=1, newBoard.row do
newBoard.map[i] = {}
for j=1, newBoard.col do
newBoard.map[i][j] = tile.new(tile.BLANK,xPos + j*newBoard.tileWidth,yPos+i*newBoard.tileHeight)
end
end
return setmetatable(newBoard, board_mt)
end
function board.new(xPos,yPos,tileWidth,tileHeight,jsonFilePath)
local t = loadJSON(jsonFilePath)
local newBoard = {
x = xPos,
y = yPos,
tileWidth = tileWidth or 32,
tileHeight = tileHeight or 32,
col = t.col,
row = t.row,
pions = {}
}
local back = display.newImageRect( "assets/background.png", 320,313, true )
back:setReferencePoint(display.TopLeftReferencePoint)
back.x = 80-0.5
back.y = 340+1+7-341+4
layer.insertImage(0,back)
local idxDir = 1
newBoard.map = {}
for i=1, newBoard.row do
newBoard.map[i] = {}
for j=1, newBoard.col do
print("tile "..t.tilemap[(i-1)*t.col+j])
if(t.tilemap[(i-1)*t.col+j] == tile.DIRECTION) then
newBoard.map[i][j] = tile.new(t.tilemap[(i-1)*t.col+j],xPos + (j-1)*newBoard.tileWidth,yPos+(i-1)*newBoard.tileHeight, newBoard.tileWidth, newBoard.tileHeight, t.direction[idxDir])
idxDir = idxDir + 1
else
newBoard.map[i][j] = tile.new(t.tilemap[(i-1)*t.col+j],xPos + (j-1)*newBoard.tileWidth,yPos+(i-1)*newBoard.tileHeight, newBoard.tileWidth, newBoard.tileHeight)
end
end
end
return setmetatable(newBoard, board_mt)
end
function loadJSON( filename )
-- set default base dir if none specified
local base = system.ResourceDirectory
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
--return decoded json string
return json.decode( contents )
else
--or return nil if file didn't ex
return nil
end
end
function board:getTileType(rowPos,colPos)
return self.map[rowPos][colPos].tile_type
end
function board:getTile(rowPos,colPos)
return self.map[rowPos][colPos]
end
function board:addPion(_pion,row,col)
table.insert(self.pions,_pion)
end
function board:removePion(_pion)
local idx = -1
for i=1,table.getn(self.pions) do
if(self.pions[i] == _pion) then
idx = i
break
end
end
if(idx >= 0) then
table.remove(self.pions,idx)
end
end
function board:getPion(row,col)
print(self.pions.numChildren)
for i=1,table.getn(self.pions) do
if(self.pions[i].row == row and self.pions[i].col == col) then
return self.pions[i]
end
end
return nil
end
return board | 0nc0m-3n4k | trunk/board.lua | Lua | mit | 3,546 |
package yuku.filechooser.demo;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.util.*;
import yuku.filechooser.*;
import yuku.filechooser.FileChooserConfig.Mode;
public class FileChooserDemoActivity extends Activity {
private static final int REQCODE_showFileChooser = 1;
private static final int REQCODE_showFolderChooser = 2;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void bShowFileChooser_click(View v) {
EditText tInitialDir = (EditText) findViewById(R.id.tInitialDir);
EditText tTitle = (EditText) findViewById(R.id.tTitle);
EditText tPattern = (EditText) findViewById(R.id.tPattern);
FileChooserConfig config = new FileChooserConfig();
config.mode = Mode.Open;
config.initialDir = tInitialDir.length() == 0 ? null : tInitialDir.getText().toString();
config.title = tTitle.length() == 0 ? null : tTitle.getText().toString();
config.pattern = tPattern.length() == 0 ? null : tPattern.getText().toString();
startActivityForResult(FileChooserActivity.createIntent(getApplicationContext(), config), REQCODE_showFileChooser);
}
public void bShowFolderChooser_click(View v) {
EditText tInitialDir = (EditText) findViewById(R.id.tInitialDir);
EditText tTitle = (EditText) findViewById(R.id.tTitle);
CheckBox cShowHidden = (CheckBox) findViewById(R.id.cShowHidden);
FolderChooserConfig config = new FolderChooserConfig();
config.roots = Arrays.asList(Environment.getExternalStorageDirectory().toString(), tInitialDir.getText().toString());
config.showHidden = cShowHidden.isChecked();
config.title = tTitle.length() == 0 ? null : tTitle.getText().toString();
startActivityForResult(FolderChooserActivity.createIntent(getApplicationContext(), config), REQCODE_showFolderChooser);
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQCODE_showFileChooser) {
}
if (requestCode == REQCODE_showFolderChooser) {
if (resultCode == RESULT_OK) {
FolderChooserResult result = FolderChooserActivity.obtainResult(data);
new AlertDialog.Builder(this)
.setTitle("Result")
.setMessage(result.selectedFolder)
.show();
}
}
}
} | 04146814d-23 | FileChooserDemo/src/yuku/filechooser/demo/FileChooserDemoActivity.java | Java | asf20 | 2,337 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type long and long.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TLongLongIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TLongLongIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public long key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue( long val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TLongLongIterator.java | Java | asf20 | 4,347 |
// ////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
/**
* Common interface for iterators that operate via the "advance" method for moving the
* cursor to the next element.
*/
public interface TAdvancingIterator extends TIterator {
/**
* Moves the iterator forward to the next entry.
*
* @throws java.util.NoSuchElementException if the iterator is already exhausted
*/
public void advance();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TAdvancingIterator.java | Java | asf20 | 1,379 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type int and Object.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TIntObjectIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TIntObjectIterator<V> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public int key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public V value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public V setValue( V val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TIntObjectIterator.java | Java | asf20 | 4,648 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type long and int.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TLongIntIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TLongIntIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public long key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public int value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public int setValue( int val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TLongIntIterator.java | Java | asf20 | 4,338 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public interface TPrimitiveIterator extends TIterator {
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext();
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove();
} // TPrimitiveIterator
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TPrimitiveIterator.java | Java | asf20 | 2,329 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type Object and int.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TObjectIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TObjectIntIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: Object_E_Iterator.template,v 1.1.2.1 2009/09/14 19:02:20 upholderoftruth Exp $
*/
public interface TObjectIntIterator<K> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public K key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public int value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public int setValue( int val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TObjectIntIterator.java | Java | asf20 | 4,652 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type int and long.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TIntLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TIntLongIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TIntLongIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public int key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue( long val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TIntLongIterator.java | Java | asf20 | 4,340 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
/**
* Common interface for all iterators used in Trove.
*/
public interface TIterator {
/**
* Returns true if the iterator can be advanced past its current location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext();
/**
* Removes the last entry returned by the iterator. The result of invoking this method
* more than once for a single entry is undefined and can leave the underlying data
* structure in a confused state.
*/
public void remove();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TIterator.java | Java | asf20 | 1,541 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for int collections.
*/
public interface TIntIterator extends TIterator {
/**
* Advances the iterator to the next element in the underlying collection
* and returns it.
*
* @return the next int in the collection
* @exception NoSuchElementException if the iterator is already exhausted
*/
public int next();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TIntIterator.java | Java | asf20 | 1,504 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type Object and long.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TObjectLongIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TObjectLongIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: Object_E_Iterator.template,v 1.1.2.1 2009/09/14 19:02:20 upholderoftruth Exp $
*/
public interface TObjectLongIterator<K> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public K key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public long value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public long setValue( long val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TObjectLongIterator.java | Java | asf20 | 4,661 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type int and int.
*
* <p>The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.</p>
*
* <p>This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.</p>
*
* <p>In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.</p>
*
* <p>Here are some sample scenarios for this class of iterator:</p>
*
* <pre>
* // accessing keys/values through an iterator:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
*
* <pre>
* // modifying values in-place through iteration:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
*
* <pre>
* // deleting entries during iteration:
* for ( TIntIntIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) {
* it.remove();
* }
* }
* </pre>
*
* <pre>
* // faster iteration by avoiding hasNext():
* TIntIntIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*/
public interface TIntIntIterator extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public int key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public int value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public int setValue( int val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TIntIntIterator.java | Java | asf20 | 4,331 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator.hash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.impl.hash.THashIterator;
/**
* Iterator for hashtables that use open addressing to resolve collisions.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TObjectHashIterator.java,v 1.1.2.4 2009/10/09 01:44:34 robeden Exp $
*/
public class TObjectHashIterator<E> extends THashIterator<E> {
protected final TObjectHash _objectHash;
public TObjectHashIterator( TObjectHash<E> hash ) {
super( hash );
_objectHash = hash;
}
@SuppressWarnings("unchecked")
protected E objectAtIndex( int index ) {
Object obj = _objectHash._set[index];
if ( obj == TObjectHash.FREE || obj == TObjectHash.REMOVED ) {
return null;
}
return (E) obj;
}
} // TObjectHashIterator
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/hash/TObjectHashIterator.java | Java | asf20 | 2,001 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for maps of type long and Object.
* <p/>
* The iterator semantics for Trove's primitive maps is slightly different
* from those defined in <tt>java.util.Iterator</tt>, but still well within
* the scope of the pattern, as defined by Gamma, et al.
* <p/>
* This iterator does <b>not</b> implicitly advance to the next entry when
* the value at the current position is retrieved. Rather, you must explicitly
* ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>,
* the <tt>value()</tt> or both. This is done so that you have the option, but not
* the obligation, to retrieve keys and/or values as your application requires, and
* without introducing wrapper objects that would carry both. As the iteration is
* stateful, access to the key/value parts of the current map entry happens in
* constant time.
* <p/>
* In practice, the iterator is akin to a "search finger" that you move from
* position to position. Read or write operations affect the current entry only and
* do not assume responsibility for moving the finger.
* <p/>
* Here are some sample scenarios for this class of iterator:
* <p/>
* <pre>
* // accessing keys/values through an iterator:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* doSomethingWithValue( it.value() );
* }
* }
* </pre>
* <p/>
* <pre>
* // modifying values in-place through iteration:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.setValue( newValueForKey( it.key() ) );
* }
* }
* </pre>
* <p/>
* <pre>
* // deleting entries during iteration:
* for ( TLongObjectIterator it = map.iterator(); it.hasNext(); ) {
* it.advance();
* if ( satisfiesCondition( it.key() ) ) {
* it.remove();
* }
* }
* </pre>
* <p/>
* <pre>
* // faster iteration by avoiding hasNext():
* TLongObjectIterator iterator = map.iterator();
* for ( int i = map.size(); i-- > 0; ) {
* iterator.advance();
* doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
* }
* </pre>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TLongObjectIterator<V> extends TAdvancingIterator {
/**
* Provides access to the key of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the key of the entry at the iterator's current position.
*/
public long key();
/**
* Provides access to the value of the mapping at the iterator's position.
* Note that you must <tt>advance()</tt> the iterator at least once
* before invoking this method.
*
* @return the value of the entry at the iterator's current position.
*/
public V value();
/**
* Replace the value of the mapping at the iterator's position with the
* specified value. Note that you must <tt>advance()</tt> the iterator at
* least once before invoking this method.
*
* @param val the value to set in the current entry
* @return the old value of the entry.
*/
public V setValue( V val );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TLongObjectIterator.java | Java | asf20 | 4,655 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.iterator;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Iterator for long collections.
*/
public interface TLongIterator extends TIterator {
/**
* Advances the iterator to the next element in the underlying collection
* and returns it.
*
* @return the next long in the collection
* @exception NoSuchElementException if the iterator is already exhausted
*/
public long next();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/iterator/TLongIterator.java | Java | asf20 | 1,508 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TIntIterator;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.TIntCollection;
import java.util.Collection;
import java.util.Set;
import java.io.Serializable;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* Created: Sat Nov 3 10:38:17 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TIntSet extends TIntCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
int getNoEntryValue();
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this set contains the specified element.
*
* @param entry an <code>int</code> value
* @return true if the set contains the specified element.
*/
boolean contains( int entry );
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>TIntIterator</code> value
*/
TIntIterator iterator();
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this set. (In other words, this method must
* allocate a new array even if this set is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this set
*/
int[] toArray();
/**
* Returns an array containing elements in this set.
*
* <p>If this set fits in the specified array with room to spare
* (i.e., the array has more elements than this set), the element in
* the array immediately following the end of the set is set to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this set <i>only</i> if the caller knows that this
* set does not contain any elements representing null.)
*
* <p>If the native array is smaller than the set size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this set are to be
* stored.
* @return an <tt>int[]</tt> containing all the elements in this set
* @throws NullPointerException if the specified array is null
*/
int[] toArray( int[] dest );
/**
* Inserts a value into the set.
*
* @param entry a <code>int</code> value
* @return true if the set was modified by the add operation
*/
boolean add( int entry );
/**
* Removes <tt>entry</tt> from the set.
*
* @param entry an <code>int</code> value
* @return true if the set was modified by the remove operation.
*/
boolean remove( int entry );
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the set to determine if all of the elements in
* <tt>TIntCollection</tt> are present.
*
* @param collection a <code>TIntCollection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( TIntCollection collection );
/**
* Tests the set to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of int primitives.
* @return true if all elements were present in the set.
*/
boolean containsAll( int[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( Collection<? extends Integer> collection );
/**
* Adds all of the elements in the <tt>TIntCollection</tt> to the set.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( TIntCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the set.
*
* @param array a <code>array</code> of int primitives.
* @return true if the set was modified by the add all operation.
*/
boolean addAll( int[] array );
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the set which are not contained in
* <tt>TIntCollection</tt>.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( TIntCollection collection );
/**
* Removes any values in the set which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of int primitives.
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( int[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TIntCollection</tt> from the set.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( TIntCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the set.
*
* @param array an <code>array</code> of int primitives.
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll( int[] array );
/**
* Empties the set.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
boolean forEach( TIntProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals( Object o );
/**
* Returns the hash code value for this set. The hash code of a set is
* defined to be the sum of the hash codes of the elements in the set.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this set
* @see Object#equals(Object)
* @see Set#equals(Object)
*/
int hashCode();
} // THashSet
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/TIntSet.java | Java | asf20 | 10,309 |
package gnu.trove.set.hash;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.list.linked.TIntLinkedList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.io.IOException;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* Created by IntelliJ IDEA.
* User: Johan
* Date: 15/03/11
* Time: 18:15
* To change this template use File | Settings | File Templates.
*/
public class TLinkedHashSet<E> extends THashSet<E> {
TIntList order;
/**
* Creates a new <code>THashSet</code> instance with the default
* capacity and load factor.
*/
public TLinkedHashSet() {
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLinkedHashSet(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashSet</code> instance containing the
* elements of <tt>collection</tt>.
*
* @param es a <code>Collection</code> value
*/
public TLinkedHashSet(Collection<? extends E> es) {
super(es);
}
/**
* initializes the Object set of this hash table.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
@Override
public int setUp(int initialCapacity) {
order = new TIntArrayList(initialCapacity) {
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length) {
int newCap = Math.max(_set.length, capacity);
int[] tmp = new int[newCap];
System.arraycopy(_data, 0, tmp, 0, _data.length);
_data = tmp;
}
}
};
return super.setUp(initialCapacity); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* Empties the set.
*/
@Override
public void clear() {
super.clear();
order.clear();
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for (Iterator<E> it = iterator(); it.hasNext();) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(it.next());
}
buf.append("}");
return buf.toString();
}
/**
* Inserts a value into the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the add operation
*/
@Override
public boolean add(E obj) {
int index = insertKey(obj);
if (index < 0) {
return false; // already present in set, nothing to add
}
if (!order.add(index))
throw new IllegalStateException("Order not changed after insert");
postInsertHook(consumeFreeSlot);
return true; // yes, we added something
}
@Override
protected void removeAt(int index) {
// Remove from order first since super.removeAt can trigger compaction
// making the index invalid afterwards
order.remove(index);
super.removeAt(index);
}
/**
* Expands the set to accommodate new values.
*
* @param newCapacity an <code>int</code> value
*/
@Override
protected void rehash(int newCapacity) {
TIntLinkedList oldOrder = new TIntLinkedList(order);
int oldSize = size();
Object oldSet[] = _set;
order.clear();
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
for (TIntIterator iterator = oldOrder.iterator(); iterator.hasNext();) {
int i = iterator.next();
E o = (E) oldSet[i];
if (o == FREE || o == REMOVED) {
throw new IllegalStateException("Iterating over empty location while rehashing");
}
if (o != FREE && o != REMOVED) {
int index = insertKey(o);
if (index < 0) { // everyone pays for this because some people can't RTFM
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet);
}
if (!order.add(index))
throw new IllegalStateException("Order not changed after insert");
}
}
}
class WriteProcedure implements TIntProcedure {
final ObjectOutput output;
IOException ioException;
WriteProcedure(ObjectOutput output) {
this.output = output;
}
public IOException getIoException() {
return ioException;
}
public boolean execute(int value) {
try {
output.writeObject(_set[value]);
} catch (IOException e) {
ioException = e;
return false;
}
return true;
}
}
@Override
protected void writeEntries(ObjectOutput out) throws IOException {
// ENTRIES
WriteProcedure writeProcedure = new WriteProcedure(out);
if (!order.forEach(writeProcedure))
throw writeProcedure.getIoException();
}
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>Iterator</code> value
*/
@Override
public TObjectHashIterator<E> iterator() {
return new TObjectHashIterator<E>(this) {
TIntIterator localIterator = order.iterator();
int lastIndex;
/**
* Moves the iterator to the next Object and returns it.
*
* @return an <code>Object</code> value
* @throws java.util.ConcurrentModificationException
* if the structure
* was changed using a method that isn't on this iterator.
* @throws java.util.NoSuchElementException
* if this is called on an
* exhausted iterator.
*/
@Override
public E next() {
lastIndex = localIterator.next();
return objectAtIndex(lastIndex);
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
@Override
public boolean hasNext() {
return localIterator.hasNext(); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
@Override
public void remove() {
// Remove for iterator first
localIterator.remove();
// the removal within removeAt() will not change the collection
// but the localIterator will remain valid
try {
_hash.tempDisableAutoCompaction();
TLinkedHashSet.this.removeAt(lastIndex);
} finally {
_hash.reenableAutoCompaction(false);
}
}
}; //To change body of overridden methods use File | Settings | File Templates.
}
class ForEachProcedure implements TIntProcedure {
boolean changed = false;
final Object[] set;
final TObjectProcedure<? super E> procedure;
public ForEachProcedure(Object[] set, TObjectProcedure<? super E> procedure) {
this.set = set;
this.procedure = procedure;
}
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(int value) {
return procedure.execute((E) set[value]);
}
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
@Override
public boolean forEach(TObjectProcedure<? super E> procedure) {
ForEachProcedure forEachProcedure = new ForEachProcedure(_set, procedure);
return order.forEach(forEachProcedure);
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/hash/TLinkedHashSet.java | Java | asf20 | 10,310 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.set.TLongSet;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.impl.*;
import gnu.trove.impl.hash.*;
import gnu.trove.TLongCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Externalizable;
import java.util.Arrays;
import java.util.Collection;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed set implementation for long primitives.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TLongHashSet extends TLongHash implements TLongSet, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>TLongHashSet</code> instance with the default
* capacity and load factor.
*/
public TLongHashSet() {
super();
}
/**
* Creates a new <code>TLongHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongHashSet( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param load_factor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongHashSet( int initialCapacity, float load_factor ) {
super( initialCapacity, load_factor );
}
/**
* Creates a new <code>TLongHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initial_capacity</tt> and
* with the specified load factor.
*
* @param initial_capacity an <code>int</code> value
* @param load_factor a <code>float</code> value
* @param no_entry_value a <code>long</code> value that represents null.
*/
public TLongHashSet( int initial_capacity, float load_factor,
long no_entry_value ) {
super( initial_capacity, load_factor, no_entry_value );
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHashSet</code> instance that is a copy
* of the existing Collection.
*
* @param collection a <tt>Collection</tt> that will be duplicated.
*/
public TLongHashSet( Collection<? extends Long> collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
addAll( collection );
}
/**
* Creates a new <code>TLongHashSet</code> instance that is a copy
* of the existing set.
*
* @param collection a <tt>TLongSet</tt> that will be duplicated.
*/
public TLongHashSet( TLongCollection collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
if ( collection instanceof TLongHashSet ) {
TLongHashSet hashset = ( TLongHashSet ) collection;
this._loadFactor = hashset._loadFactor;
this.no_entry_value = hashset.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
addAll( collection );
}
/**
* Creates a new <code>TLongHashSet</code> instance containing the
* elements of <tt>array</tt>.
*
* @param array an array of <code>long</code> primitives
*/
public TLongHashSet( long[] array ) {
this( Math.max( array.length, DEFAULT_CAPACITY ) );
addAll( array );
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongHashIterator( this );
}
/** {@inheritDoc} */
public long[] toArray() {
long[] result = new long[ size() ];
long[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
result[j++] = set[i];
}
}
return result;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
long[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = set[i];
}
}
if ( dest.length > _size ) {
dest[_size] = no_entry_value;
}
return dest;
}
/** {@inheritDoc} */
public boolean add( long val ) {
int index = insertKey(val);
if ( index < 0 ) {
return false; // already present in set, nothing to add
}
postInsertHook( consumeFreeSlot );
return true; // yes, we added something
}
/** {@inheritDoc} */
public boolean remove( long val ) {
int index = index(val);
if ( index >= 0 ) {
removeAt( index );
return true;
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
boolean changed = false;
for ( Long element : collection ) {
long e = element.longValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( add( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
super.clear();
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
set[i] = no_entry_value;
states[i] = FREE;
}
}
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldSet[] = _set;
byte oldStates[] = _states;
_set = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldSet[i];
int index = insertKey(o);
}
}
}
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongSet ) ) {
return false;
}
TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
StringBuilder buffy = new StringBuilder( _size * 2 + 2 );
buffy.append("{");
for ( int i = _states.length, j = 1; i-- > 0; ) {
if ( _states[i] == FULL ) {
buffy.append( _set[i] );
if ( j++ < _size ) {
buffy.append( "," );
}
}
}
buffy.append("}");
return buffy.toString();
}
class TLongHashIterator extends THashPrimitiveIterator implements TLongIterator {
/** the collection on which the iterator operates */
private final TLongHash _hash;
/** {@inheritDoc} */
public TLongHashIterator( TLongHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _hash._set[_index];
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 1 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// LOAD FACTOR -- Added version 1
out.writeFloat( _loadFactor );
// NO ENTRY VALUE -- Added version 1
out.writeLong( no_entry_value );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
int version = in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
if ( version >= 1 ) {
// LOAD FACTOR
_loadFactor = in.readFloat();
// NO ENTRY VALUE
no_entry_value = in.readLong();
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
// ENTRIES
setUp( size );
while ( size-- > 0 ) {
long val = in.readLong();
add( val );
}
}
} // TIntHashSet
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/hash/TLongHashSet.java | Java | asf20 | 14,702 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.set.TIntSet;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.impl.*;
import gnu.trove.impl.hash.*;
import gnu.trove.TIntCollection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Externalizable;
import java.util.Arrays;
import java.util.Collection;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed set implementation for int primitives.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TIntHashSet extends TIntHash implements TIntSet, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>TIntHashSet</code> instance with the default
* capacity and load factor.
*/
public TIntHashSet() {
super();
}
/**
* Creates a new <code>TIntHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntHashSet( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param load_factor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntHashSet( int initialCapacity, float load_factor ) {
super( initialCapacity, load_factor );
}
/**
* Creates a new <code>TIntHashSet</code> instance with a prime
* capacity equal to or greater than <tt>initial_capacity</tt> and
* with the specified load factor.
*
* @param initial_capacity an <code>int</code> value
* @param load_factor a <code>float</code> value
* @param no_entry_value a <code>int</code> value that represents null.
*/
public TIntHashSet( int initial_capacity, float load_factor,
int no_entry_value ) {
super( initial_capacity, load_factor, no_entry_value );
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHashSet</code> instance that is a copy
* of the existing Collection.
*
* @param collection a <tt>Collection</tt> that will be duplicated.
*/
public TIntHashSet( Collection<? extends Integer> collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
addAll( collection );
}
/**
* Creates a new <code>TIntHashSet</code> instance that is a copy
* of the existing set.
*
* @param collection a <tt>TIntSet</tt> that will be duplicated.
*/
public TIntHashSet( TIntCollection collection ) {
this( Math.max( collection.size(), DEFAULT_CAPACITY ) );
if ( collection instanceof TIntHashSet ) {
TIntHashSet hashset = ( TIntHashSet ) collection;
this._loadFactor = hashset._loadFactor;
this.no_entry_value = hashset.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
addAll( collection );
}
/**
* Creates a new <code>TIntHashSet</code> instance containing the
* elements of <tt>array</tt>.
*
* @param array an array of <code>int</code> primitives
*/
public TIntHashSet( int[] array ) {
this( Math.max( array.length, DEFAULT_CAPACITY ) );
addAll( array );
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntHashIterator( this );
}
/** {@inheritDoc} */
public int[] toArray() {
int[] result = new int[ size() ];
int[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
result[j++] = set[i];
}
}
return result;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
int[] set = _set;
byte[] states = _states;
for ( int i = states.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = set[i];
}
}
if ( dest.length > _size ) {
dest[_size] = no_entry_value;
}
return dest;
}
/** {@inheritDoc} */
public boolean add( int val ) {
int index = insertKey(val);
if ( index < 0 ) {
return false; // already present in set, nothing to add
}
postInsertHook( consumeFreeSlot );
return true; // yes, we added something
}
/** {@inheritDoc} */
public boolean remove( int val ) {
int index = index(val);
if ( index >= 0 ) {
removeAt( index );
return true;
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
boolean changed = false;
for ( Integer element : collection ) {
int e = element.intValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( add( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
super.clear();
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
set[i] = no_entry_value;
states[i] = FREE;
}
}
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldSet[] = _set;
byte oldStates[] = _states;
_set = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldSet[i];
int index = insertKey(o);
}
}
}
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntSet ) ) {
return false;
}
TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
StringBuilder buffy = new StringBuilder( _size * 2 + 2 );
buffy.append("{");
for ( int i = _states.length, j = 1; i-- > 0; ) {
if ( _states[i] == FULL ) {
buffy.append( _set[i] );
if ( j++ < _size ) {
buffy.append( "," );
}
}
}
buffy.append("}");
return buffy.toString();
}
class TIntHashIterator extends THashPrimitiveIterator implements TIntIterator {
/** the collection on which the iterator operates */
private final TIntHash _hash;
/** {@inheritDoc} */
public TIntHashIterator( TIntHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _hash._set[_index];
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 1 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// LOAD FACTOR -- Added version 1
out.writeFloat( _loadFactor );
// NO ENTRY VALUE -- Added version 1
out.writeInt( no_entry_value );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
int version = in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
if ( version >= 1 ) {
// LOAD FACTOR
_loadFactor = in.readFloat();
// NO ENTRY VALUE
no_entry_value = in.readInt();
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
// ENTRIES
setUp( size );
while ( size-- > 0 ) {
int val = in.readInt();
add( val );
}
}
} // TIntHashSet
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/hash/TIntHashSet.java | Java | asf20 | 14,642 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set.hash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.impl.HashFunctions;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.array.ToObjectArrayProceedure;
import gnu.trove.iterator.hash.TObjectHashIterator;
import java.io.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.Arrays;
import java.lang.reflect.Array;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: THashSet.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $
*/
public class THashSet<E> extends TObjectHash<E>
implements Set<E>, Iterable<E>, Externalizable {
static final long serialVersionUID = 1L;
/**
* Creates a new <code>THashSet</code> instance with the default
* capacity and load factor.
*/
public THashSet() {
super();
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THashSet(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashSet</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashSet</code> instance containing the
* elements of <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
*/
public THashSet(Collection<? extends E> collection) {
this(collection.size());
addAll(collection);
}
/**
* Inserts a value into the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the add operation
*/
public boolean add(E obj) {
int index = insertKey(obj);
if (index < 0) {
return false; // already present in set, nothing to add
}
postInsertHook(consumeFreeSlot);
return true; // yes, we added something
}
@SuppressWarnings({"SimplifiableIfStatement"})
public boolean equals(Object other) {
if (!(other instanceof Set)) {
return false;
}
Set that = (Set) other;
if (that.size() != this.size()) {
return false;
}
return containsAll(that);
}
public int hashCode() {
HashProcedure p = new HashProcedure();
forEach(p);
return p.getHashCode();
}
private final class HashProcedure implements TObjectProcedure<E> {
private int h = 0;
public int getHashCode() {
return h;
}
public final boolean execute(E key) {
h += HashFunctions.hash(key);
return true;
}
}
/**
* Expands the set to accommodate new values.
*
* @param newCapacity an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
protected void rehash(int newCapacity) {
int oldCapacity = _set.length;
int oldSize = size();
Object oldSet[] = _set;
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
int count = 0;
for (int i = oldCapacity; i-- > 0;) {
E o = (E) oldSet[i];
if (o != FREE && o != REMOVED) {
int index = insertKey(o);
if (index < 0) { // everyone pays for this because some people can't RTFM
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet);
}
//
count++;
}
}
// Last check: size before and after should be the same
reportPotentialConcurrentMod(size(), oldSize);
}
/**
* Returns a new array containing the objects in the set.
*
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public Object[] toArray() {
Object[] result = new Object[size()];
forEach(new ToObjectArrayProceedure(result));
return result;
}
/**
* Returns a typed array of the objects in the set.
*
* @param a an <code>Object[]</code> value
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size) {
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
}
forEach(new ToObjectArrayProceedure(a));
// If this collection fits in the specified array with room to
// spare (i.e., the array has more elements than this
// collection), the element in the array immediately following
// the end of the collection is set to null. This is useful in
// determining the length of this collection only if the
// caller knows that this collection does not contain any null
// elements.)
if (a.length > size) {
a[size] = null;
}
return a;
}
/**
* Empties the set.
*/
public void clear() {
super.clear();
Arrays.fill(_set, 0, _set.length, FREE);
}
/**
* Removes <tt>obj</tt> from the set.
*
* @param obj an <code>Object</code> value
* @return true if the set was modified by the remove operation.
*/
@SuppressWarnings({"unchecked"})
public boolean remove(Object obj) {
int index = index(obj);
if (index >= 0) {
removeAt(index);
return true;
}
return false;
}
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>Iterator</code> value
*/
@SuppressWarnings({"unchecked"})
public TObjectHashIterator<E> iterator() {
return new TObjectHashIterator<E>(this);
}
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
public boolean containsAll(Collection<?> collection) {
for (Iterator i = collection.iterator(); i.hasNext();) {
if (!contains(i.next())) {
return false;
}
}
return true;
}
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
public boolean addAll(Collection<? extends E> collection) {
boolean changed = false;
int size = collection.size();
ensureCapacity(size);
Iterator<? extends E> it = collection.iterator();
while (size-- > 0) {
if (add(it.next())) {
changed = true;
}
}
return changed;
}
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll(Collection<?> collection) {
boolean changed = false;
int size = collection.size();
Iterator it;
it = collection.iterator();
while (size-- > 0) {
if (remove(it.next())) {
changed = true;
}
}
return changed;
}
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll(Collection<?> collection) {
boolean changed = false;
int size = size();
Iterator<E> it = iterator();
while (size-- > 0) {
if (!collection.contains(it.next())) {
it.remove();
changed = true;
}
}
return changed;
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEach(new TObjectProcedure<E>() {
private boolean first = true;
public boolean execute(Object value) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(1);
// NOTE: Super was not written in version 0
super.writeExternal(out);
// NUMBER OF ENTRIES
out.writeInt(_size);
// ENTRIES
writeEntries(out);
}
protected void writeEntries(ObjectOutput out) throws IOException {
for (int i = _set.length; i-- > 0;) {
if (_set[i] != REMOVED && _set[i] != FREE) {
out.writeObject(_set[i]);
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
byte version = in.readByte();
// NOTE: super was not written in version 0
if (version != 0) {
super.readExternal(in);
}
// NUMBER OF ENTRIES
int size = in.readInt();
setUp(size);
// ENTRIES
while (size-- > 0) {
E val = (E) in.readObject();
add(val);
}
}
} // THashSet
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/hash/THashSet.java | Java | asf20 | 11,904 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TLongIterator;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.TLongCollection;
import java.util.Collection;
import java.util.Set;
import java.io.Serializable;
/**
* An implementation of the <tt>Set</tt> interface that uses an
* open-addressed hash table to store its contents.
*
* Created: Sat Nov 3 10:38:17 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $
*/
public interface TLongSet extends TLongCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
long getNoEntryValue();
/**
* Returns the number of elements in this set (its cardinality). If this
* set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this set (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this set contains the specified element.
*
* @param entry an <code>long</code> value
* @return true if the set contains the specified element.
*/
boolean contains( long entry );
/**
* Creates an iterator over the values of the set. The iterator
* supports element deletion.
*
* @return an <code>TLongIterator</code> value
*/
TLongIterator iterator();
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this set. (In other words, this method must
* allocate a new array even if this set is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this set
*/
long[] toArray();
/**
* Returns an array containing elements in this set.
*
* <p>If this set fits in the specified array with room to spare
* (i.e., the array has more elements than this set), the element in
* the array immediately following the end of the set is set to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this set <i>only</i> if the caller knows that this
* set does not contain any elements representing null.)
*
* <p>If the native array is smaller than the set size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this set are to be
* stored.
* @return an <tt>long[]</tt> containing all the elements in this set
* @throws NullPointerException if the specified array is null
*/
long[] toArray( long[] dest );
/**
* Inserts a value into the set.
*
* @param entry a <code>long</code> value
* @return true if the set was modified by the add operation
*/
boolean add( long entry );
/**
* Removes <tt>entry</tt> from the set.
*
* @param entry an <code>long</code> value
* @return true if the set was modified by the remove operation.
*/
boolean remove( long entry );
/**
* Tests the set to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the set to determine if all of the elements in
* <tt>TLongCollection</tt> are present.
*
* @param collection a <code>TLongCollection</code> value
* @return true if all elements were present in the set.
*/
boolean containsAll( TLongCollection collection );
/**
* Tests the set to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of long primitives.
* @return true if all elements were present in the set.
*/
boolean containsAll( long[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( Collection<? extends Long> collection );
/**
* Adds all of the elements in the <tt>TLongCollection</tt> to the set.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the add all operation.
*/
boolean addAll( TLongCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the set.
*
* @param array a <code>array</code> of long primitives.
* @return true if the set was modified by the add all operation.
*/
boolean addAll( long[] array );
/**
* Removes any values in the set which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the set which are not contained in
* <tt>TLongCollection</tt>.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( TLongCollection collection );
/**
* Removes any values in the set which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of long primitives.
* @return true if the set was modified by the retain all operation
*/
boolean retainAll( long[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the set.
*
* @param collection a <code>Collection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TLongCollection</tt> from the set.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the set was modified by the remove all operation.
*/
boolean removeAll( TLongCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the set.
*
* @param array an <code>array</code> of long primitives.
* @return true if the set was modified by the remove all operation.
*/
public boolean removeAll( long[] array );
/**
* Empties the set.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
boolean forEach( TLongProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals( Object o );
/**
* Returns the hash code value for this set. The hash code of a set is
* defined to be the sum of the hash codes of the elements in the set.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this set
* @see Object#equals(Object)
* @see Set#equals(Object)
*/
int hashCode();
} // THashSet
| 04146814d-23 | SimpleTrove/src/gnu/trove/set/TLongSet.java | Java | asf20 | 10,346 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TIntCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of int keys and int values.
*/
public interface TIntIntMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public int getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public int getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>int</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int put( int key, int value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>int</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int putIfAbsent( int key, int value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Integer, ? extends Integer> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TIntIntMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int get( int key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int remove( int key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TIntSet</tt>
*
* @return the keys of the map as a <tt>TIntSet</tt>
*/
public TIntSet keySet();
/**
* Returns the keys of the map as an array of <tt>int</tt> values.
*
* @return the keys of the map as an array of <tt>int</tt> values.
*/
public int[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public int[] keys( int[] array );
/**
* Returns the values of the map as a <tt>TIntCollection</tt>
*
* @return the values of the map as a <tt>TIntCollection</tt>
*/
public TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values( int[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( int val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( int key );
/**
* @return a TIntIntIterator with access to this map's keys and values
*/
public TIntIntIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOIntIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntIntProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntIntProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( int key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( int key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( int key, int adjust_amount, int put_amount );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TIntIntMap.java | Java | asf20 | 9,232 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TIntCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of long keys and int values.
*/
public interface TLongIntMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public long getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public int getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>long</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int put( long key, int value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>long</code> value
* @param value an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int putIfAbsent( long key, int value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Long, ? extends Integer> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TLongIntMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int get( long key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public int remove( long key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TLongSet</tt>
*
* @return the keys of the map as a <tt>TLongSet</tt>
*/
public TLongSet keySet();
/**
* Returns the keys of the map as an array of <tt>long</tt> values.
*
* @return the keys of the map as an array of <tt>long</tt> values.
*/
public long[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public long[] keys( long[] array );
/**
* Returns the values of the map as a <tt>TIntCollection</tt>
*
* @return the values of the map as a <tt>TIntCollection</tt>
*/
public TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public int[] values( int[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( int val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( long key );
/**
* @return a TLongIntIterator with access to this map's keys and values
*/
public TLongIntIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOLongIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongIntProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongIntProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( long key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( long key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( long key, int adjust_amount, int put_amount );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TLongIntMap.java | Java | asf20 | 9,261 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TLongCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of long keys and long values.
*/
public interface TLongLongMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public long getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public long getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>long</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long put( long key, long value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>long</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long putIfAbsent( long key, long value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Long, ? extends Long> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TLongLongMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long get( long key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long remove( long key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TLongSet</tt>
*
* @return the keys of the map as a <tt>TLongSet</tt>
*/
public TLongSet keySet();
/**
* Returns the keys of the map as an array of <tt>long</tt> values.
*
* @return the keys of the map as an array of <tt>long</tt> values.
*/
public long[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public long[] keys( long[] array );
/**
* Returns the values of the map as a <tt>TLongCollection</tt>
*
* @return the values of the map as a <tt>TLongCollection</tt>
*/
public TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values( long[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( long val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( long key );
/**
* @return a TLongLongIterator with access to this map's keys and values
*/
public TLongLongIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOLongLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongLongProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongLongProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( long key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( long key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( long key, long adjust_amount, long put_amount );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TLongLongMap.java | Java | asf20 | 9,291 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongObjectProcedure;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TLongSet;
import java.util.Collection;
import java.util.Map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of long keys and Object values.
*/
public interface TLongObjectMap<V> {
// Query Operations
/**
* Returns the value that represents null in the {@link #keySet()}.
* The default value is generally zero, but can be changed during
* construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
long getNoEntryKey();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>key.equals(k)</tt>. (There can be at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( long key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( Object value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>long</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
V get( long key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(long) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryKey()
*/
V put( long key, V value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or null
* if none was found.
*/
V putIfAbsent( long key, V value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>key.equals(k)</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>long</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
V remove( long key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(long,Object) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends Long, ? extends V> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TLongObjectMap<? extends V> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link TLongSet} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
TLongSet keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
long[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
long[] keys( long[] array );
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
Collection<V> valueCollection();
/**
* Returns the values of the map as an array of <tt>long</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>long</tt> values.
*/
V[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>long</tt> values.
*/
V[] values( V[] array );
/**
* Returns a <tt>TLongObjectIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TLongObjectIterator</tt> with access to this map's keys and values.
*/
public TLongObjectIterator<V> iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TObjectProcedure<? super V> procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TLongObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TLongObjectProcedure<? super V> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues( TObjectFunction<V,V> function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TLongObjectProcedure<? super V> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TLongObjectMap.java | Java | asf20 | 16,930 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TIntIntMap;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for int keys and int values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TIntIntHashMap extends TIntIntHash implements TIntIntMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient int[] _values;
/**
* Creates a new <code>TIntIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntIntHashMap() {
super();
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntIntHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>int</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>int</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TIntIntHashMap( int initialCapacity, float loadFactor,
int noEntryKey, int noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TIntIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>int</tt> array containing the keys for the matching values.
* @param values a <tt>int</tt> array containing the values.
*/
public TIntIntHashMap( int[] keys, int[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TIntIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TIntIntMap</tt> that will be duplicated.
*/
public TIntIntHashMap( TIntIntMap map ) {
super( map.size() );
if ( map instanceof TIntIntHashMap ) {
TIntIntHashMap hashmap = ( TIntIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
int oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public int put( int key, int value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( int key, int value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private int doPut( int key, int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends Integer> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet() ) {
this.put( entry.getKey().intValue(), entry.getValue().intValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntIntMap map ) {
ensureCapacity( map.size() );
TIntIntIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public int get( int key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public int remove( int key ) {
int prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TIntSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public int[] keys( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
byte[] states = _states;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public TIntIntIterator iterator() {
return new TIntIntHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TIntProcedure procedure ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TIntIntProcedure procedure ) {
byte[] states = _states;
int[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TIntIntProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( int key ) {
return adjustValue( key, ( int ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( int key, int amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( int key, int adjust_amount, int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TIntSet {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIntKeyHashIterator( TIntIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntIntHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntIntHashMap.this.keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntIntHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return no_entry_value != TIntIntHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntIntHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntIntHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntIntHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntIntHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TIntSet)) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TIntProcedure() {
private boolean first = true;
public boolean execute( int key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIntValueHashIterator( TIntIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
int[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntIntHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TIntIntKeyHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntIntKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntIntValueHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntIntValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntIntHashIterator extends THashPrimitiveIterator implements TIntIntIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TIntIntHashMap</tt> we will be iterating over.
*/
TIntIntHashIterator( TIntIntHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _set[_index];
}
/** {@inheritDoc} */
public int value() {
return _values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntIntMap ) ) {
return false;
}
TIntIntMap that = ( TIntIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
int[] values = _values;
byte[] states = _states;
int this_no_entry_value = getNoEntryValue();
int that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
int key = _set[i];
int that_value = that.get( key );
int this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TIntIntProcedure() {
private boolean first = true;
public boolean execute( int key, int value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeInt( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
int val = in.readInt();
put(key, val);
}
}
} // TIntIntHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TIntIntHashMap.java | Java | asf20 | 35,362 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TLongLongMap;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for long keys and long values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TLongLongHashMap extends TLongLongHash implements TLongLongMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient long[] _values;
/**
* Creates a new <code>TLongLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongLongHashMap() {
super();
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongLongHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>long</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>long</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TLongLongHashMap( int initialCapacity, float loadFactor,
long noEntryKey, long noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TLongLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>long</tt> array containing the keys for the matching values.
* @param values a <tt>long</tt> array containing the values.
*/
public TLongLongHashMap( long[] keys, long[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TLongLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TLongLongMap</tt> that will be duplicated.
*/
public TLongLongHashMap( TLongLongMap map ) {
super( map.size() );
if ( map instanceof TLongLongHashMap ) {
TLongLongHashMap hashmap = ( TLongLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
long oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public long put( long key, long value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( long key, long value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private long doPut( long key, long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends Long> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Long, ? extends Long> entry : map.entrySet() ) {
this.put( entry.getKey().longValue(), entry.getValue().longValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongLongMap map ) {
ensureCapacity( map.size() );
TLongLongIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public long get( long key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public long remove( long key ) {
long prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TLongSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public long[] keys( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
byte[] states = _states;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public TLongLongIterator iterator() {
return new TLongLongHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TLongProcedure procedure ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TLongLongProcedure procedure ) {
byte[] states = _states;
long[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TLongLongProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( long key ) {
return adjustValue( key, ( long ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( long key, long amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( long key, long adjust_amount, long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TLongSet {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongLongKeyHashIterator( TLongLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongLongHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongLongHashMap.this.keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongLongHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return no_entry_value != TLongLongHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongLongHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongLongHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongLongHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongLongHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TLongSet)) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TLongProcedure() {
private boolean first = true;
public boolean execute( long key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongLongValueHashIterator( TLongLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
long[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongLongHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TLongLongKeyHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongLongKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongLongValueHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongLongValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongLongHashIterator extends THashPrimitiveIterator implements TLongLongIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TLongLongHashMap</tt> we will be iterating over.
*/
TLongLongHashIterator( TLongLongHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _set[_index];
}
/** {@inheritDoc} */
public long value() {
return _values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongLongMap ) ) {
return false;
}
TLongLongMap that = ( TLongLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
long[] values = _values;
byte[] states = _states;
long this_no_entry_value = getNoEntryValue();
long that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
long key = _set[i];
long that_value = that.get( key );
long this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TLongLongProcedure() {
private boolean first = true;
public boolean execute( long key, long value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeLong( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
long val = in.readLong();
put(key, val);
}
}
} // TLongLongHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TLongLongHashMap.java | Java | asf20 | 35,618 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.*;
import gnu.trove.procedure.TLongObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.iterator.TPrimitiveIterator;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TLongSet;
import gnu.trove.TLongCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for long keys and Object values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TLongObjectHashMap<V> extends TLongHash implements
TLongObjectMap<V>, Externalizable {
static final long serialVersionUID = 1L;
private final TLongObjectProcedure<V> PUT_ALL_PROC = new TLongObjectProcedure<V>() {
public boolean execute( long key, V value) {
put( key, value );
return true;
}
};
/** the values of the map */
protected transient V[] _values;
/** the value that represents null in the key set. */
protected long no_entry_key;
/**
* Creates a new <code>TLongObjectHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongObjectHashMap() {
super();
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongObjectHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_key = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongObjectHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_key = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TLongObjectHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryKey the value used to represent null in the key set.
*/
public TLongObjectHashMap( int initialCapacity, float loadFactor, long noEntryKey ) {
super( initialCapacity, loadFactor );
no_entry_key = noEntryKey;
}
/**
* Creates a new <code>TLongObjectHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TLongObjectMap</tt> to be copied.
*/
public TLongObjectHashMap( TLongObjectMap<? extends V> map ) {
this( map.size(), 0.5f, map.getNoEntryKey() );
putAll( map );
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = ( V[] ) new Object[capacity];
return capacity;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
V oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = (V[]) new Object[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey(o);
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public long getNoEntryKey() {
return no_entry_key;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
}
/** {@inheritDoc} */
public V get( long key ) {
int index = index( key );
return index < 0 ? null : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public V put( long key, V value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public V putIfAbsent( long key, V value ) {
int index = insertKey( key );
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
@SuppressWarnings({"unchecked"})
private V doPut( V value, int index ) {
V previous = null;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public V remove( long key ) {
V prev = null;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = null;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends V> map ) {
Set<? extends Map.Entry<? extends Long,? extends V>> set = map.entrySet();
for ( Map.Entry<? extends Long,? extends V> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongObjectMap<? extends V> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _states, 0, _states.length, FREE );
Arrays.fill( _values, 0, _values.length, null );
}
// Views
/** {@inheritDoc} */
public TLongSet keySet() {
return new KeyView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public long[] keys( long[] dest ) {
if ( dest.length < _size ) {
dest = new long[_size];
}
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = k[i];
}
}
return dest;
}
/** {@inheritDoc} */
public Collection<V> valueCollection() {
return new ValueView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values() {
V[] vals = ( V[] ) new Object[size()];
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values( V[] dest ) {
if ( dest.length < _size ) {
dest = ( V[] ) java.lang.reflect.Array.newInstance(
dest.getClass().getComponentType(), _size);
}
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = ( V ) v[i];
}
}
return dest;
}
/** {@inheritDoc} */
public TLongObjectIterator<V> iterator() {
return new TLongObjectHashIterator<V>( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TObjectProcedure<? super V> procedure ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TLongObjectProcedure<? super V> procedure ) {
byte[] states = _states;
long[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean retainEntries( TLongObjectProcedure<? super V> procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public void transformValues( TObjectFunction<V,V> function ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongObjectMap ) ) {
return false;
}
TLongObjectMap that = ( TLongObjectMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TLongObjectIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
long key = iter.key();
Object value = iter.value();
if ( value == null ) {
if ( !( that.get( key ) == null && that.containsKey( key ) ) ) {
return false;
}
} else {
if ( !value.equals( that.get( key ) ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
( values[i] == null ? 0 : values[i].hashCode() );
}
}
return hashcode;
}
class KeyView implements TLongSet {
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _size == 0;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongObjectHashMap.this.containsKey( entry );
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongHashIterator( TLongObjectHashMap.this );
}
/** {@inheritDoc} */
public long[] toArray() {
return keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return keys( dest );
}
/** {@inheritDoc} */
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return null != TLongObjectHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( ! TLongObjectHashMap.this.containsKey(
( ( Long ) element ).longValue() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
if ( collection == this ) {
return true;
}
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongObjectHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongObjectHashMap.this.containsKey( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
//noinspection SuspiciousMethodCalls
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongObjectHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongObjectHashMap.this.forEachKey( procedure );
}
/** {@inheritDoc) */
public boolean equals( Object other ) {
if (! ( other instanceof TLongSet ) ) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( _set[i] );
}
}
return buf.toString();
}
class TLongHashIterator extends THashPrimitiveIterator implements TLongIterator {
/** the collection on which the iterator operates */
private final TLongHash _hash;
/** {@inheritDoc} */
public TLongHashIterator( TLongHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _hash._set[_index];
}
}
}
/** a view onto the values of the map. */
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TLongObjectValueHashIterator( TLongObjectHashMap.this ) {
protected V objectAtIndex( int index ) {
return _values[index];
}
};
}
public boolean containsElement( V value ) {
return containsValue( value );
}
public boolean removeElement( V value ) {
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
if ( value == values[i] ||
( null != values[i] && values[i].equals( value ) ) ) {
removeAt( i );
return true;
}
}
}
return false;
}
class TLongObjectValueHashIterator extends THashPrimitiveIterator
implements Iterator<V> {
protected final TLongObjectHashMap _map;
public TLongObjectValueHashIterator( TLongObjectHashMap map ) {
super( map );
_map = map;
}
@SuppressWarnings("unchecked")
protected V objectAtIndex( int index ) {
byte[] states = _states;
Object value = _map._values[index];
if ( states[index] != FULL ) {
return null;
}
return ( V ) value;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public V next() {
moveToNextIndex();
return ( V ) _map._values[_index];
}
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TLongObjectHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TLongObjectHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TLongObjectHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TLongObjectHashIterator<V> extends THashPrimitiveIterator
implements TLongObjectIterator<V> {
/** the collection being iterated over */
private final TLongObjectHashMap<V> _map;
/**
* Creates an iterator over the specified map
*
* @param map map to iterate over.
*/
public TLongObjectHashIterator( TLongObjectHashMap<V> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _map._set[_index];
}
/** {@inheritDoc} */
public V value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public V setValue( V val ) {
V old = value();
_map._values[_index] = val;
return old;
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeObject( _values[i] );
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
V val = (V) in.readObject();
put(key, val);
}
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TLongObjectProcedure<V>() {
private boolean first = true;
public boolean execute(long key, Object value) {
if ( first ) first = false;
else buf.append( "," );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
} // TLongObjectHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TLongObjectHashMap.java | Java | asf20 | 28,706 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TLongIntMap;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for long keys and int values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TLongIntHashMap extends TLongIntHash implements TLongIntMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient int[] _values;
/**
* Creates a new <code>TLongIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TLongIntHashMap() {
super();
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongIntHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TLongIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>long</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>int</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TLongIntHashMap( int initialCapacity, float loadFactor,
long noEntryKey, int noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TLongIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>long</tt> array containing the keys for the matching values.
* @param values a <tt>int</tt> array containing the values.
*/
public TLongIntHashMap( long[] keys, int[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TLongIntHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TLongIntMap</tt> that will be duplicated.
*/
public TLongIntHashMap( TLongIntMap map ) {
super( map.size() );
if ( map instanceof TLongIntHashMap ) {
TLongIntHashMap hashmap = ( TLongIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( long ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
long oldKeys[] = _set;
int oldVals[] = _values;
byte oldStates[] = _states;
_set = new long[newCapacity];
_values = new int[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
long o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public int put( long key, int value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( long key, int value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private int doPut( long key, int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Long, ? extends Integer> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Long, ? extends Integer> entry : map.entrySet() ) {
this.put( entry.getKey().longValue(), entry.getValue().intValue() );
}
}
/** {@inheritDoc} */
public void putAll( TLongIntMap map ) {
ensureCapacity( map.size() );
TLongIntIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public int get( long key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public int remove( long key ) {
int prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TLongSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public long[] keys() {
long[] keys = new long[size()];
long[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public long[] keys( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
byte[] states = _states;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( long key ) {
return contains( key );
}
/** {@inheritDoc} */
public TLongIntIterator iterator() {
return new TLongIntHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TLongProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TIntProcedure procedure ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TLongIntProcedure procedure ) {
byte[] states = _states;
long[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
byte[] states = _states;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TLongIntProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
long[] keys = _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( long key ) {
return adjustValue( key, ( int ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( long key, int amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( long key, int adjust_amount, int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TLongSet {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongIntKeyHashIterator( TLongIntHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TLongIntHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TLongIntHashMap.this.keys();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TLongIntHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
return no_entry_value != TLongIntHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TLongIntHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongIntHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TLongIntHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TLongIntMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TLongIntHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TLongSet)) {
return false;
}
final TLongSet that = ( TLongSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TLongProcedure() {
private boolean first = true;
public boolean execute( long key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TLongIntValueHashIterator( TLongIntHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TLongIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TLongIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TLongIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
long[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TLongIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TLongIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TLongIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TLongIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TLongIntHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TLongIntKeyHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongIntKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongIntValueHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TLongIntValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TLongIntHashIterator extends THashPrimitiveIterator implements TLongIntIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TLongIntHashMap</tt> we will be iterating over.
*/
TLongIntHashIterator( TLongIntHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public long key() {
return _set[_index];
}
/** {@inheritDoc} */
public int value() {
return _values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TLongIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TLongIntMap ) ) {
return false;
}
TLongIntMap that = ( TLongIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
int[] values = _values;
byte[] states = _states;
int this_no_entry_value = getNoEntryValue();
int that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
long key = _set[i];
int that_value = that.get( key );
int this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TLongIntProcedure() {
private boolean first = true;
public boolean execute( long key, int value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeLong( _set[i] );
out.writeInt( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
long key = in.readLong();
int val = in.readInt();
put(key, val);
}
}
} // TLongIntHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TLongIntHashMap.java | Java | asf20 | 35,481 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.*;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.iterator.TPrimitiveIterator;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TIntSet;
import gnu.trove.TIntCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for int keys and Object values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TIntObjectHashMap<V> extends TIntHash implements
TIntObjectMap<V>, Externalizable {
static final long serialVersionUID = 1L;
private final TIntObjectProcedure<V> PUT_ALL_PROC = new TIntObjectProcedure<V>() {
public boolean execute( int key, V value) {
put( key, value );
return true;
}
};
/** the values of the map */
protected transient V[] _values;
/** the value that represents null in the key set. */
protected int no_entry_key;
/**
* Creates a new <code>TIntObjectHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntObjectHashMap() {
super();
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntObjectHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_key = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntObjectHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_key = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TIntObjectHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryKey the value used to represent null in the key set.
*/
public TIntObjectHashMap( int initialCapacity, float loadFactor, int noEntryKey ) {
super( initialCapacity, loadFactor );
no_entry_key = noEntryKey;
}
/**
* Creates a new <code>TIntObjectHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TIntObjectMap</tt> to be copied.
*/
public TIntObjectHashMap( TIntObjectMap<? extends V> map ) {
this( map.size(), 0.5f, map.getNoEntryKey() );
putAll( map );
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = ( V[] ) new Object[capacity];
return capacity;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
V oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = (V[]) new Object[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey(o);
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public int getNoEntryKey() {
return no_entry_key;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
}
/** {@inheritDoc} */
public V get( int key ) {
int index = index( key );
return index < 0 ? null : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public V put( int key, V value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public V putIfAbsent( int key, V value ) {
int index = insertKey( key );
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
@SuppressWarnings({"unchecked"})
private V doPut( V value, int index ) {
V previous = null;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public V remove( int key ) {
V prev = null;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = null;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends V> map ) {
Set<? extends Map.Entry<? extends Integer,? extends V>> set = map.entrySet();
for ( Map.Entry<? extends Integer,? extends V> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntObjectMap<? extends V> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _states, 0, _states.length, FREE );
Arrays.fill( _values, 0, _values.length, null );
}
// Views
/** {@inheritDoc} */
public TIntSet keySet() {
return new KeyView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public int[] keys( int[] dest ) {
if ( dest.length < _size ) {
dest = new int[_size];
}
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = k[i];
}
}
return dest;
}
/** {@inheritDoc} */
public Collection<V> valueCollection() {
return new ValueView();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values() {
V[] vals = ( V[] ) new Object[size()];
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public V[] values( V[] dest ) {
if ( dest.length < _size ) {
dest = ( V[] ) java.lang.reflect.Array.newInstance(
dest.getClass().getComponentType(), _size);
}
V[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
dest[j++] = ( V ) v[i];
}
}
return dest;
}
/** {@inheritDoc} */
public TIntObjectIterator<V> iterator() {
return new TIntObjectHashIterator<V>( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TObjectProcedure<? super V> procedure ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TIntObjectProcedure<? super V> procedure ) {
byte[] states = _states;
int[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public boolean retainEntries( TIntObjectProcedure<? super V> procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public void transformValues( TObjectFunction<V,V> function ) {
byte[] states = _states;
V[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/** {@inheritDoc} */
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntObjectMap ) ) {
return false;
}
TIntObjectMap that = ( TIntObjectMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TIntObjectIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
int key = iter.key();
Object value = iter.value();
if ( value == null ) {
if ( !( that.get( key ) == null && that.containsKey( key ) ) ) {
return false;
}
} else {
if ( !value.equals( that.get( key ) ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
( values[i] == null ? 0 : values[i].hashCode() );
}
}
return hashcode;
}
class KeyView implements TIntSet {
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _size == 0;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntObjectHashMap.this.containsKey( entry );
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntHashIterator( TIntObjectHashMap.this );
}
/** {@inheritDoc} */
public int[] toArray() {
return keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return keys( dest );
}
/** {@inheritDoc} */
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return null != TIntObjectHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( ! TIntObjectHashMap.this.containsKey(
( ( Integer ) element ).intValue() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
if ( collection == this ) {
return true;
}
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntObjectHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntObjectHashMap.this.containsKey( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
//noinspection SuspiciousMethodCalls
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntObjectHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntObjectHashMap.this.forEachKey( procedure );
}
/** {@inheritDoc) */
public boolean equals( Object other ) {
if (! ( other instanceof TIntSet ) ) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
boolean first = true;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( _set[i] );
}
}
return buf.toString();
}
class TIntHashIterator extends THashPrimitiveIterator implements TIntIterator {
/** the collection on which the iterator operates */
private final TIntHash _hash;
/** {@inheritDoc} */
public TIntHashIterator( TIntHash hash ) {
super( hash );
this._hash = hash;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _hash._set[_index];
}
}
}
/** a view onto the values of the map. */
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TIntObjectValueHashIterator( TIntObjectHashMap.this ) {
protected V objectAtIndex( int index ) {
return _values[index];
}
};
}
public boolean containsElement( V value ) {
return containsValue( value );
}
public boolean removeElement( V value ) {
V[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
if ( value == values[i] ||
( null != values[i] && values[i].equals( value ) ) ) {
removeAt( i );
return true;
}
}
}
return false;
}
class TIntObjectValueHashIterator extends THashPrimitiveIterator
implements Iterator<V> {
protected final TIntObjectHashMap _map;
public TIntObjectValueHashIterator( TIntObjectHashMap map ) {
super( map );
_map = map;
}
@SuppressWarnings("unchecked")
protected V objectAtIndex( int index ) {
byte[] states = _states;
Object value = _map._values[index];
if ( states[index] != FULL ) {
return null;
}
return ( V ) value;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public V next() {
moveToNextIndex();
return ( V ) _map._values[_index];
}
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TIntObjectHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TIntObjectHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TIntObjectHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TIntObjectHashIterator<V> extends THashPrimitiveIterator
implements TIntObjectIterator<V> {
/** the collection being iterated over */
private final TIntObjectHashMap<V> _map;
/**
* Creates an iterator over the specified map
*
* @param map map to iterate over.
*/
public TIntObjectHashIterator( TIntObjectHashMap<V> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _map._set[_index];
}
/** {@inheritDoc} */
public V value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public V setValue( V val ) {
V old = value();
_map._values[_index] = val;
return old;
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeObject( _values[i] );
}
}
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
V val = (V) in.readObject();
put(key, val);
}
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TIntObjectProcedure<V>() {
private boolean first = true;
public boolean execute(int key, Object value) {
if ( first ) first = false;
else buf.append( "," );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
} // TIntObjectHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TIntObjectHashMap.java | Java | asf20 | 28,600 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.map.TIntLongMap;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.iterator.*;
import gnu.trove.iterator.hash.*;
import gnu.trove.impl.hash.*;
import gnu.trove.impl.HashFunctions;
import gnu.trove.*;
import java.io.*;
import java.util.*;
/**
* An open addressed Map implementation for int keys and long values.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $
*/
public class TIntLongHashMap extends TIntLongHash implements TIntLongMap, Externalizable {
static final long serialVersionUID = 1L;
/** the values of the map */
protected transient long[] _values;
/**
* Creates a new <code>TIntLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TIntLongHashMap() {
super();
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntLongHashMap( int initialCapacity ) {
super( initialCapacity );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TIntLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
* @param noEntryKey a <code>int</code> value that represents
* <tt>null</tt> for the Key set.
* @param noEntryValue a <code>long</code> value that represents
* <tt>null</tt> for the Value set.
*/
public TIntLongHashMap( int initialCapacity, float loadFactor,
int noEntryKey, long noEntryValue ) {
super( initialCapacity, loadFactor, noEntryKey, noEntryValue );
}
/**
* Creates a new <code>TIntLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param keys a <tt>int</tt> array containing the keys for the matching values.
* @param values a <tt>long</tt> array containing the values.
*/
public TIntLongHashMap( int[] keys, long[] values ) {
super( Math.max( keys.length, values.length ) );
int size = Math.min( keys.length, values.length );
for ( int i = 0; i < size; i++ ) {
this.put( keys[i], values[i] );
}
}
/**
* Creates a new <code>TIntLongHashMap</code> instance containing
* all of the entries in the map passed in.
*
* @param map a <tt>TIntLongMap</tt> that will be duplicated.
*/
public TIntLongHashMap( TIntLongMap map ) {
super( map.size() );
if ( map instanceof TIntLongHashMap ) {
TIntLongHashMap hashmap = ( TIntLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_key = hashmap.no_entry_key;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_key != ( int ) 0 ) {
Arrays.fill( _set, this.no_entry_key );
}
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
/** {@inheritDoc} */
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
int oldKeys[] = _set;
long oldVals[] = _values;
byte oldStates[] = _states;
_set = new int[newCapacity];
_values = new long[newCapacity];
_states = new byte[newCapacity];
for ( int i = oldCapacity; i-- > 0; ) {
if( oldStates[i] == FULL ) {
int o = oldKeys[i];
int index = insertKey( o );
_values[index] = oldVals[i];
}
}
}
/** {@inheritDoc} */
public long put( int key, long value ) {
int index = insertKey( key );
return doPut( key, value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( int key, long value ) {
int index = insertKey( key );
if (index < 0)
return _values[-index - 1];
return doPut( key, value, index );
}
private long doPut( int key, long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public void putAll( Map<? extends Integer, ? extends Long> map ) {
ensureCapacity( map.size() );
// could optimize this for cases when map instanceof THashMap
for ( Map.Entry<? extends Integer, ? extends Long> entry : map.entrySet() ) {
this.put( entry.getKey().intValue(), entry.getValue().longValue() );
}
}
/** {@inheritDoc} */
public void putAll( TIntLongMap map ) {
ensureCapacity( map.size() );
TIntLongIterator iter = map.iterator();
while ( iter.hasNext() ) {
iter.advance();
this.put( iter.key(), iter.value() );
}
}
/** {@inheritDoc} */
public long get( int key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, no_entry_key );
Arrays.fill( _values, 0, _values.length, no_entry_value );
Arrays.fill( _states, 0, _states.length, FREE );
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public long remove( int key ) {
long prev = no_entry_value;
int index = index( key );
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/** {@inheritDoc} */
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
/** {@inheritDoc} */
public TIntSet keySet() {
return new TKeyView();
}
/** {@inheritDoc} */
public int[] keys() {
int[] keys = new int[size()];
int[] k = _set;
byte[] states = _states;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
keys[j++] = k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public int[] keys( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] keys = _set;
byte[] states = _states;
for ( int i = keys.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = keys[i];
}
}
return array;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TValueView();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
byte[] states = _states;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( states[i] == FULL ) {
array[j++] = v[i];
}
}
return array;
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
byte[] states = _states;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsKey( int key ) {
return contains( key );
}
/** {@inheritDoc} */
public TIntLongIterator iterator() {
return new TIntLongHashIterator( this );
}
/** {@inheritDoc} */
public boolean forEachKey( TIntProcedure procedure ) {
return forEach( procedure );
}
/** {@inheritDoc} */
public boolean forEachValue( TLongProcedure procedure ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachEntry( TIntLongProcedure procedure ) {
byte[] states = _states;
int[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
byte[] states = _states;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
values[i] = function.execute( values[i] );
}
}
}
/** {@inheritDoc} */
public boolean retainEntries( TIntLongProcedure procedure ) {
boolean modified = false;
byte[] states = _states;
int[] keys = _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) {
removeAt( i );
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/** {@inheritDoc} */
public boolean increment( int key ) {
return adjustValue( key, ( long ) 1 );
}
/** {@inheritDoc} */
public boolean adjustValue( int key, long amount ) {
int index = index( key );
if (index < 0) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( int key, long adjust_amount, long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
byte previousState = _states[index];
if ( isNewMapping ) {
postInsertHook(consumeFreeSlot);
}
return newValue;
}
/** a view onto the keys of the map. */
protected class TKeyView implements TIntSet {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntLongKeyHashIterator( TIntLongHashMap.this );
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_key;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TIntLongHashMap.this.contains( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TIntLongHashMap.this.keys();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TIntLongHashMap.this.keys( dest );
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
return no_entry_value != TIntLongHashMap.this.remove( entry );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TIntLongHashMap.this.containsKey( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntLongHashMap.this.containsKey( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TIntLongHashMap.this.contains( element ) ) {
return false;
}
}
return true;
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/**
* Unsupported when operating upon a Key Set view of a TIntLongMap
* <p/>
* {@inheritDoc}
*/
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] set = _set;
byte[] states = _states;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TIntLongHashMap.this.forEachKey( procedure );
}
@Override
public boolean equals( Object other ) {
if (! (other instanceof TIntSet)) {
return false;
}
final TIntSet that = ( TIntSet ) other;
if ( that.size() != this.size() ) {
return false;
}
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
if ( ! that.contains( _set[i] ) ) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hashcode = 0;
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] );
}
}
return hashcode;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachKey( new TIntProcedure() {
private boolean first = true;
public boolean execute( int key ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( key );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
/** a view onto the values of the map. */
protected class TValueView implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TIntLongValueHashIterator( TIntLongHashMap.this );
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TIntLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TIntLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TIntLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
int[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TIntLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TIntLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TIntLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
byte[] states = _states;
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TIntLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TIntLongHashMap.this.forEachValue( procedure );
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
}
class TIntLongKeyHashIterator extends THashPrimitiveIterator implements TIntIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntLongKeyHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _set[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntLongValueHashIterator extends THashPrimitiveIterator implements TLongIterator {
/**
* Creates an iterator over the specified map
*
* @param hash the <tt>TPrimitiveHash</tt> we will be iterating over.
*/
TIntLongValueHashIterator( TPrimitiveHash hash ) {
super( hash );
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
class TIntLongHashIterator extends THashPrimitiveIterator implements TIntLongIterator {
/**
* Creates an iterator over the specified map
*
* @param map the <tt>TIntLongHashMap</tt> we will be iterating over.
*/
TIntLongHashIterator( TIntLongHashMap map ) {
super( map );
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
public int key() {
return _set[_index];
}
/** {@inheritDoc} */
public long value() {
return _values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_values[_index] = val;
return old;
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TIntLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
}
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( ! ( other instanceof TIntLongMap ) ) {
return false;
}
TIntLongMap that = ( TIntLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
long[] values = _values;
byte[] states = _states;
long this_no_entry_value = getNoEntryValue();
long that_no_entry_value = that.getNoEntryValue();
for ( int i = values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
int key = _set[i];
long that_value = that.get( key );
long this_value = values[i];
if ( ( this_value != that_value ) &&
( this_value != this_no_entry_value ) &&
( that_value != that_no_entry_value ) ) {
return false;
}
}
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int hashcode = 0;
byte[] states = _states;
for ( int i = _values.length; i-- > 0; ) {
if ( states[i] == FULL ) {
hashcode += HashFunctions.hash( _set[i] ) ^
HashFunctions.hash( _values[i] );
}
}
return hashcode;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachEntry( new TIntLongProcedure() {
private boolean first = true;
public boolean execute( int key, long value ) {
if ( first ) first = false;
else buf.append( ", " );
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append( "}" );
return buf.toString();
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _states.length; i-- > 0; ) {
if ( _states[i] == FULL ) {
out.writeInt( _set[i] );
out.writeLong( _values[i] );
}
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
int key = in.readInt();
long val = in.readLong();
put(key, val);
}
}
} // TIntLongHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TIntLongHashMap.java | Java | asf20 | 35,499 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.THash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.procedure.TObjectIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TObjectIntIterator;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.function.TIntFunction;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.TIntCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for Object keys and int values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TObjectIntHashMap<K> extends TObjectHash<K>
implements TObjectIntMap<K>, Externalizable {
static final long serialVersionUID = 1L;
private final TObjectIntProcedure<K> PUT_ALL_PROC = new TObjectIntProcedure<K>() {
public boolean execute(K key, int value) {
put(key, value);
return true;
}
};
/** the values of the map */
protected transient int[] _values;
/** the value that represents null */
protected int no_entry_value;
/**
* Creates a new <code>TObjectIntHashMap</code> instance with the default
* capacity and load factor.
*/
public TObjectIntHashMap() {
super();
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectIntHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TObjectIntHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectIntHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryValue the value used to represent null.
*/
public TObjectIntHashMap( int initialCapacity, float loadFactor, int noEntryValue ) {
super( initialCapacity, loadFactor );
no_entry_value = noEntryValue;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, no_entry_value );
}
}
/**
* Creates a new <code>TObjectIntHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TObjectIntMap</tt> to be copied.
*/
public TObjectIntHashMap( TObjectIntMap<? extends K> map ) {
this( map.size(), 0.5f, map.getNoEntryValue() );
if ( map instanceof TObjectIntHashMap ) {
TObjectIntHashMap hashmap = ( TObjectIntHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( int ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
public int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new int[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
//noinspection unchecked
K oldKeys[] = ( K[] ) _set;
int oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill( _set, FREE );
_values = new int[newCapacity];
Arrays.fill( _values, no_entry_value );
for ( int i = oldCapacity; i-- > 0; ) {
if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) {
K o = oldKeys[i];
int index = insertKey(o);
if ( index < 0 ) {
throwObjectContractViolation( _set[ (-index -1) ], o);
}
_set[index] = o;
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public boolean containsKey( Object key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( int val ) {
Object[] keys = _set;
int[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int get( Object key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public int put( K key, int value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public int putIfAbsent( K key, int value ) {
int index = insertKey(key);
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
private int doPut( int value, int index ) {
int previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
//noinspection unchecked
_values[index] = value;
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public int remove( Object key ) {
int prev = no_entry_value;
int index = index(key);
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/**
* Removes the mapping at <tt>index</tt> from the map.
* This method is used internally and public mainly because
* of packaging reasons. Caveat Programmer.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends K, ? extends Integer> map ) {
Set<? extends Map.Entry<? extends K,? extends Integer>> set = map.entrySet();
for ( Map.Entry<? extends K,? extends Integer> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TObjectIntMap<? extends K> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, FREE );
Arrays.fill( _values, 0, _values.length, no_entry_value );
}
// Views
/** {@inheritDoc} */
public Set<K> keySet() {
return new KeyView();
}
/** {@inheritDoc} */
public Object[] keys() {
//noinspection unchecked
K[] keys = ( K[] ) new Object[size()];
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
keys[j++] = ( K ) k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public K[] keys( K[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = ( K[] ) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
a[j++] = ( K ) k[i];
}
}
return a;
}
/** {@inheritDoc} */
public TIntCollection valueCollection() {
return new TIntValueCollection();
}
/** {@inheritDoc} */
public int[] values() {
int[] vals = new int[size()];
int[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public int[] values( int[] array ) {
int size = size();
if ( array.length < size ) {
array = new int[size];
}
int[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
array[j++] = v[i];
}
}
if ( array.length > size ) {
array[size] = no_entry_value;
}
return array;
}
/**
* @return an iterator over the entries in this map
*/
public TObjectIntIterator<K> iterator() {
return new TObjectIntHashIterator<K>( this );
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantCast"})
public boolean increment( K key ) {
//noinspection RedundantCast
return adjustValue( key, (int)1 );
}
/** {@inheritDoc} */
public boolean adjustValue( K key, int amount ) {
int index = index(key);
if ( index < 0 ) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public int adjustOrPutValue( final K key, final int adjust_amount,
final int put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final int newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
//noinspection unchecked
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return newValue;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure ) {
return forEach( procedure );
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED
&& ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TObjectIntProcedure<? super K> procedure ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( ( K ) keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectIntProcedure<? super K> procedure ) {
boolean modified = false;
//noinspection unchecked
K[] keys = ( K[] ) _set;
int[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( keys[i], values[i] ) ) {
removeAt(i);
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function ) {
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != null && keys[i] != REMOVED ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectIntMap ) ) {
return false;
}
TObjectIntMap that = ( TObjectIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectIntIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
int value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
Object[] keys = _set;
int[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
hashcode += HashFunctions.hash( values[i] ) ^
( keys[i] == null ? 0 : keys[i].hashCode() );
}
}
return hashcode;
}
/** a view onto the keys of the map. */
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator( TObjectIntHashMap.this );
}
public boolean removeElement( K key ) {
return no_entry_value != TObjectIntHashMap.this.remove( key );
}
public boolean containsElement( K key ) {
return TObjectIntHashMap.this.contains( key );
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TObjectIntHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TObjectIntHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TObjectIntHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TIntValueCollection implements TIntCollection {
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TObjectIntValueHashIterator();
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( int entry ) {
return TObjectIntHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public int[] toArray() {
return TObjectIntHashMap.this.values();
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
return TObjectIntHashMap.this.values( dest );
}
public boolean add( int entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( int entry ) {
int[] values = _values;
Object[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int ele = ( ( Integer ) element ).intValue();
if ( ! TObjectIntHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TObjectIntHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int element : array ) {
if ( ! TObjectIntHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] values = _values;
Object[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( set[i] != FREE
&& set[i] != REMOVED
&& ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TObjectIntHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
return TObjectIntHashMap.this.forEachValue( procedure );
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TIntProcedure() {
private boolean first = true;
public boolean execute( int value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
class TObjectIntValueHashIterator implements TIntIterator {
protected THash _hash = TObjectIntHashMap.this;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/** Creates an iterator over the specified map */
TObjectIntValueHashIterator() {
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/** {@inheritDoc} */
public boolean hasNext() {
return nextIndex() >= 0;
}
/** {@inheritDoc} */
public int next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for
// bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TObjectIntHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = TObjectIntHashMap.this._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE ||
set[i] == TObjectHash.REMOVED ) ) {
// do nothing
}
return i;
}
}
}
class TObjectIntHashIterator<K> extends TObjectHashIterator<K>
implements TObjectIntIterator<K> {
/** the collection being iterated over */
private final TObjectIntHashMap<K> _map;
public TObjectIntHashIterator( TObjectIntHashMap<K> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public K key() {
return ( K ) _map._set[_index];
}
/** {@inheritDoc} */
public int value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public int setValue( int val ) {
int old = value();
_map._values[_index] = val;
return old;
}
}
// Externalization
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _set.length; i-- > 0; ) {
if ( _set[i] != REMOVED && _set[i] != FREE ) {
out.writeObject( _set[i] );
out.writeInt( _values[i] );
}
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = ( K ) in.readObject();
int val = in.readInt();
put(key, val);
}
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry( new TObjectIntProcedure<K>() {
private boolean first = true;
public boolean execute( K key, int value ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( key ).append( "=" ).append( value );
return true;
}
});
buf.append( "}" );
return buf.toString();
}
} // TObjectIntHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TObjectIntHashMap.java | Java | asf20 | 32,882 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.THash;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.procedure.TObjectLongProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TObjectLongIterator;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.function.TLongFunction;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.TLongCollection;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed Map implementation for Object keys and long values.
*
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
*/
public class TObjectLongHashMap<K> extends TObjectHash<K>
implements TObjectLongMap<K>, Externalizable {
static final long serialVersionUID = 1L;
private final TObjectLongProcedure<K> PUT_ALL_PROC = new TObjectLongProcedure<K>() {
public boolean execute(K key, long value) {
put(key, value);
return true;
}
};
/** the values of the map */
protected transient long[] _values;
/** the value that represents null */
protected long no_entry_value;
/**
* Creates a new <code>TObjectLongHashMap</code> instance with the default
* capacity and load factor.
*/
public TObjectLongHashMap() {
super();
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectLongHashMap( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TObjectLongHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
}
/**
* Creates a new <code>TObjectLongHashMap</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param noEntryValue the value used to represent null.
*/
public TObjectLongHashMap( int initialCapacity, float loadFactor, long noEntryValue ) {
super( initialCapacity, loadFactor );
no_entry_value = noEntryValue;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, no_entry_value );
}
}
/**
* Creates a new <code>TObjectLongHashMap</code> that contains the entries
* in the map passed to it.
*
* @param map the <tt>TObjectLongMap</tt> to be copied.
*/
public TObjectLongHashMap( TObjectLongMap<? extends K> map ) {
this( map.size(), 0.5f, map.getNoEntryValue() );
if ( map instanceof TObjectLongHashMap ) {
TObjectLongHashMap hashmap = ( TObjectLongHashMap ) map;
this._loadFactor = hashmap._loadFactor;
this.no_entry_value = hashmap.no_entry_value;
//noinspection RedundantCast
if ( this.no_entry_value != ( long ) 0 ) {
Arrays.fill( _values, this.no_entry_value );
}
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
putAll( map );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
public int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_values = new long[capacity];
return capacity;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
protected void rehash( int newCapacity ) {
int oldCapacity = _set.length;
//noinspection unchecked
K oldKeys[] = ( K[] ) _set;
long oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill( _set, FREE );
_values = new long[newCapacity];
Arrays.fill( _values, no_entry_value );
for ( int i = oldCapacity; i-- > 0; ) {
if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) {
K o = oldKeys[i];
int index = insertKey(o);
if ( index < 0 ) {
throwObjectContractViolation( _set[ (-index -1) ], o);
}
_set[index] = o;
_values[index] = oldVals[i];
}
}
}
// Query Operations
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public boolean containsKey( Object key ) {
return contains( key );
}
/** {@inheritDoc} */
public boolean containsValue( long val ) {
Object[] keys = _set;
long[] vals = _values;
for ( int i = vals.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public long get( Object key ) {
int index = index( key );
return index < 0 ? no_entry_value : _values[index];
}
// Modification Operations
/** {@inheritDoc} */
public long put( K key, long value ) {
int index = insertKey( key );
return doPut( value, index );
}
/** {@inheritDoc} */
public long putIfAbsent( K key, long value ) {
int index = insertKey(key);
if ( index < 0 )
return _values[-index - 1];
return doPut( value, index );
}
private long doPut( long value, int index ) {
long previous = no_entry_value;
boolean isNewMapping = true;
if ( index < 0 ) {
index = -index -1;
previous = _values[index];
isNewMapping = false;
}
//noinspection unchecked
_values[index] = value;
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return previous;
}
/** {@inheritDoc} */
public long remove( Object key ) {
long prev = no_entry_value;
int index = index(key);
if ( index >= 0 ) {
prev = _values[index];
removeAt( index ); // clear key,state; adjust size
}
return prev;
}
/**
* Removes the mapping at <tt>index</tt> from the map.
* This method is used internally and public mainly because
* of packaging reasons. Caveat Programmer.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_values[index] = no_entry_value;
super.removeAt( index ); // clear key, state; adjust size
}
// Bulk Operations
/** {@inheritDoc} */
public void putAll( Map<? extends K, ? extends Long> map ) {
Set<? extends Map.Entry<? extends K,? extends Long>> set = map.entrySet();
for ( Map.Entry<? extends K,? extends Long> entry : set ) {
put( entry.getKey(), entry.getValue() );
}
}
/** {@inheritDoc} */
public void putAll( TObjectLongMap<? extends K> map ){
map.forEachEntry( PUT_ALL_PROC );
}
/** {@inheritDoc} */
public void clear() {
super.clear();
Arrays.fill( _set, 0, _set.length, FREE );
Arrays.fill( _values, 0, _values.length, no_entry_value );
}
// Views
/** {@inheritDoc} */
public Set<K> keySet() {
return new KeyView();
}
/** {@inheritDoc} */
public Object[] keys() {
//noinspection unchecked
K[] keys = ( K[] ) new Object[size()];
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
keys[j++] = ( K ) k[i];
}
}
return keys;
}
/** {@inheritDoc} */
public K[] keys( K[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = ( K[] ) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Object[] k = _set;
for ( int i = k.length, j = 0; i-- > 0; ) {
if ( k[i] != FREE && k[i] != REMOVED ) {
//noinspection unchecked
a[j++] = ( K ) k[i];
}
}
return a;
}
/** {@inheritDoc} */
public TLongCollection valueCollection() {
return new TLongValueCollection();
}
/** {@inheritDoc} */
public long[] values() {
long[] vals = new long[size()];
long[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
vals[j++] = v[i];
}
}
return vals;
}
/** {@inheritDoc} */
public long[] values( long[] array ) {
int size = size();
if ( array.length < size ) {
array = new long[size];
}
long[] v = _values;
Object[] keys = _set;
for ( int i = v.length, j = 0; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
array[j++] = v[i];
}
}
if ( array.length > size ) {
array[size] = no_entry_value;
}
return array;
}
/**
* @return an iterator over the entries in this map
*/
public TObjectLongIterator<K> iterator() {
return new TObjectLongHashIterator<K>( this );
}
/** {@inheritDoc} */
@SuppressWarnings({"RedundantCast"})
public boolean increment( K key ) {
//noinspection RedundantCast
return adjustValue( key, (long)1 );
}
/** {@inheritDoc} */
public boolean adjustValue( K key, long amount ) {
int index = index(key);
if ( index < 0 ) {
return false;
} else {
_values[index] += amount;
return true;
}
}
/** {@inheritDoc} */
public long adjustOrPutValue( final K key, final long adjust_amount,
final long put_amount ) {
int index = insertKey( key );
final boolean isNewMapping;
final long newValue;
if ( index < 0 ) {
index = -index -1;
newValue = ( _values[index] += adjust_amount );
isNewMapping = false;
} else {
newValue = ( _values[index] = put_amount );
isNewMapping = true;
}
//noinspection unchecked
if ( isNewMapping ) {
postInsertHook( consumeFreeSlot );
}
return newValue;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure ) {
return forEach( procedure );
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED
&& ! procedure.execute( values[i] ) ) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry( TObjectLongProcedure<? super K> procedure ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( ( K ) keys[i], values[i] ) ) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectLongProcedure<? super K> procedure ) {
boolean modified = false;
//noinspection unchecked
K[] keys = ( K[] ) _set;
long[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for ( int i = keys.length; i-- > 0; ) {
if ( keys[i] != FREE
&& keys[i] != REMOVED
&& ! procedure.execute( keys[i], values[i] ) ) {
removeAt(i);
modified = true;
}
}
}
finally {
reenableAutoCompaction( true );
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function ) {
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != null && keys[i] != REMOVED ) {
values[i] = function.execute( values[i] );
}
}
}
// Comparison and hashing
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectLongMap ) ) {
return false;
}
TObjectLongMap that = ( TObjectLongMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectLongIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
long value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
}
/** {@inheritDoc} */
public int hashCode() {
int hashcode = 0;
Object[] keys = _set;
long[] values = _values;
for ( int i = values.length; i-- > 0; ) {
if ( keys[i] != FREE && keys[i] != REMOVED ) {
hashcode += HashFunctions.hash( values[i] ) ^
( keys[i] == null ? 0 : keys[i].hashCode() );
}
}
return hashcode;
}
/** a view onto the keys of the map. */
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator( TObjectLongHashMap.this );
}
public boolean removeElement( K key ) {
return no_entry_value != TObjectLongHashMap.this.remove( key );
}
public boolean containsElement( K key ) {
return TObjectLongHashMap.this.contains( key );
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract boolean removeElement( E key );
public abstract boolean containsElement( E key );
@SuppressWarnings({"unchecked"})
public boolean contains( Object key ) {
return containsElement( (E) key );
}
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
return removeElement( (E) o );
}
public void clear() {
TObjectLongHashMap.this.clear();
}
public boolean add( E obj ) {
throw new UnsupportedOperationException();
}
public int size() {
return TObjectLongHashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for ( int i = 0; e.hasNext(); i++ ) {
result[i] = e.next();
}
return result;
}
public <T> T[] toArray( T[] a ) {
int size = size();
if ( a.length < size ) {
//noinspection unchecked
a = (T[]) java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size );
}
Iterator<E> it = iterator();
Object[] result = a;
for ( int i = 0; i < size; i++ ) {
result[i] = it.next();
}
if ( a.length > size ) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return TObjectLongHashMap.this.isEmpty();
}
public boolean addAll( Collection<? extends E> collection ) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean changed = false;
Iterator<E> i = iterator();
while ( i.hasNext() ) {
if ( !collection.contains( i.next() ) ) {
i.remove();
changed = true;
}
}
return changed;
}
}
class TLongValueCollection implements TLongCollection {
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TObjectLongValueHashIterator();
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return _size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return 0 == _size;
}
/** {@inheritDoc} */
public boolean contains( long entry ) {
return TObjectLongHashMap.this.containsValue( entry );
}
/** {@inheritDoc} */
public long[] toArray() {
return TObjectLongHashMap.this.values();
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
return TObjectLongHashMap.this.values( dest );
}
public boolean add( long entry ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean remove( long entry ) {
long[] values = _values;
Object[] set = _set;
for ( int i = values.length; i-- > 0; ) {
if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) {
removeAt( i );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long ele = ( ( Long ) element ).longValue();
if ( ! TObjectLongHashMap.this.containsValue( ele ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
if ( ! TObjectLongHashMap.this.containsValue( iter.next() ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( long element : array ) {
if ( ! TObjectLongHashMap.this.containsValue( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] values = _values;
Object[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( set[i] != FREE
&& set[i] != REMOVED
&& ( Arrays.binarySearch( array, values[i] ) < 0) ) {
removeAt( i );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( this == collection ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove( array[i] ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void clear() {
TObjectLongHashMap.this.clear();
}
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
return TObjectLongHashMap.this.forEachValue( procedure );
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
forEachValue( new TLongProcedure() {
private boolean first = true;
public boolean execute( long value ) {
if ( first ) {
first = false;
} else {
buf.append( ", " );
}
buf.append( value );
return true;
}
} );
buf.append( "}" );
return buf.toString();
}
class TObjectLongValueHashIterator implements TLongIterator {
protected THash _hash = TObjectLongHashMap.this;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/** Creates an iterator over the specified map */
TObjectLongValueHashIterator() {
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/** {@inheritDoc} */
public boolean hasNext() {
return nextIndex() >= 0;
}
/** {@inheritDoc} */
public long next() {
moveToNextIndex();
return _values[_index];
}
/** @{inheritDoc} */
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for
// bug 1642768.
try {
_hash.tempDisableAutoCompaction();
TObjectLongHashMap.this.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = TObjectLongHashMap.this._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE ||
set[i] == TObjectHash.REMOVED ) ) {
// do nothing
}
return i;
}
}
}
class TObjectLongHashIterator<K> extends TObjectHashIterator<K>
implements TObjectLongIterator<K> {
/** the collection being iterated over */
private final TObjectLongHashMap<K> _map;
public TObjectLongHashIterator( TObjectLongHashMap<K> map ) {
super( map );
this._map = map;
}
/** {@inheritDoc} */
public void advance() {
moveToNextIndex();
}
/** {@inheritDoc} */
@SuppressWarnings({"unchecked"})
public K key() {
return ( K ) _map._set[_index];
}
/** {@inheritDoc} */
public long value() {
return _map._values[_index];
}
/** {@inheritDoc} */
public long setValue( long val ) {
long old = value();
_map._values[_index] = val;
return old;
}
}
// Externalization
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
// NUMBER OF ENTRIES
out.writeInt( _size );
// ENTRIES
for ( int i = _set.length; i-- > 0; ) {
if ( _set[i] != REMOVED && _set[i] != FREE ) {
out.writeObject( _set[i] );
out.writeLong( _values[i] );
}
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// NUMBER OF ENTRIES
int size = in.readInt();
setUp( size );
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = ( K ) in.readObject();
long val = in.readLong();
put(key, val);
}
}
/** {@inheritDoc} */
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry( new TObjectLongProcedure<K>() {
private boolean first = true;
public boolean execute( K key, long value ) {
if ( first ) first = false;
else buf.append( "," );
buf.append( key ).append( "=" ).append( value );
return true;
}
});
buf.append( "}" );
return buf.toString();
}
} // TObjectLongHashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/TObjectLongHashMap.java | Java | asf20 | 33,014 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map.hash;
import gnu.trove.function.TObjectFunction;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.hash.TObjectHash;
import gnu.trove.iterator.hash.TObjectHashIterator;
import gnu.trove.map.TMap;
import gnu.trove.procedure.TObjectObjectProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
/**
* An implementation of the Map interface which uses an open addressed
* hash table to store its contents.
* <p/>
* Created: Sun Nov 4 08:52:45 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: THashMap.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $
*/
public class THashMap<K, V> extends TObjectHash<K> implements TMap<K, V>, Externalizable {
static final long serialVersionUID = 1L;
/**
* the values of the map
*/
protected transient V[] _values;
/**
* Creates a new <code>THashMap</code> instance with the default
* capacity and load factor.
*/
public THashMap() {
super();
}
/**
* Creates a new <code>THashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the default load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THashMap(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>THashMap</code> instance with a prime
* capacity equal to or greater than <tt>initialCapacity</tt> and
* with the specified load factor.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Creates a new <code>THashMap</code> instance which contains the
* key/value pairs in <tt>map</tt>.
*
* @param map a <code>Map</code> value
*/
public THashMap(Map<? extends K, ? extends V> map) {
this(map.size());
putAll(map);
}
/**
* Creates a new <code>THashMap</code> instance which contains the
* key/value pairs in <tt>map</tt>.
*
* @param map a <code>Map</code> value
*/
public THashMap(THashMap<? extends K, ? extends V> map) {
this(map.size());
putAll(map);
}
/**
* initialize the value array of the map.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
public int setUp(int initialCapacity) {
int capacity;
capacity = super.setUp(initialCapacity);
//noinspection unchecked
_values = (V[]) new Object[capacity];
return capacity;
}
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V put(K key, V value) {
// insertKey() inserts the key if a slot if found and returns the index
int index = insertKey(key);
return doPut(value, index);
}
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V putIfAbsent(K key, V value) {
// insertKey() inserts the key if a slot if found and returns the index
int index = insertKey(key);
if (index < 0) {
return _values[-index - 1];
}
return doPut(value, index);
}
private V doPut(V value, int index) {
V previous = null;
boolean isNewMapping = true;
if (index < 0) {
index = -index - 1;
previous = _values[index];
isNewMapping = false;
}
_values[index] = value;
if (isNewMapping) {
postInsertHook(consumeFreeSlot);
}
return previous;
}
/**
* Compares this map with another map for equality of their stored
* entries.
*
* @param other an <code>Object</code> value
* @return a <code>boolean</code> value
*/
@SuppressWarnings({"unchecked", "SimplifiableIfStatement"})
public boolean equals(Object other) {
if (!(other instanceof Map)) {
return false;
}
Map<K, V> that = (Map<K, V>) other;
if (that.size() != this.size()) {
return false;
}
return forEachEntry(new EqProcedure<K, V>(that));
}
public int hashCode() {
HashProcedure p = new HashProcedure();
forEachEntry(p);
return p.getHashCode();
}
public String toString() {
final StringBuilder buf = new StringBuilder("{");
forEachEntry(new TObjectObjectProcedure<K, V>() {
private boolean first = true;
public boolean execute(K key, V value) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(key);
buf.append("=");
buf.append(value);
return true;
}
});
buf.append("}");
return buf.toString();
}
private final class HashProcedure implements TObjectObjectProcedure<K, V> {
private int h = 0;
public int getHashCode() {
return h;
}
public final boolean execute(K key, V value) {
h += HashFunctions.hash(key) ^ (value == null ? 0 : value.hashCode());
return true;
}
}
private final class EqProcedure<K, V> implements TObjectObjectProcedure<K, V> {
private final Map<K, V> _otherMap;
EqProcedure(Map<K, V> otherMap) {
_otherMap = otherMap;
}
public final boolean execute(K key, V value) {
// Check to make sure the key is there. This avoids problems that come up with
// null values. Since it is only caused in that cause, only do this when the
// value is null (to avoid extra work).
if (value == null && !_otherMap.containsKey(key)) {
return false;
}
V oValue = _otherMap.get(key);
return oValue == value || (oValue != null &&
THashMap.this.equals(oValue, value));
}
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey(TObjectProcedure<? super K> procedure) {
return forEach(procedure);
}
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue(TObjectProcedure<? super V> procedure) {
V[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if (set[i] != FREE
&& set[i] != REMOVED
&& !procedure.execute(values[i])) {
return false;
}
}
return true;
}
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TObjectObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry(TObjectObjectProcedure<? super K, ? super V> procedure) {
Object[] keys = _set;
V[] values = _values;
for (int i = keys.length; i-- > 0;) {
if (keys[i] != FREE
&& keys[i] != REMOVED
&& !procedure.execute((K) keys[i], values[i])) {
return false;
}
}
return true;
}
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
@SuppressWarnings({"unchecked"})
public boolean retainEntries(TObjectObjectProcedure<? super K, ? super V> procedure) {
boolean modified = false;
Object[] keys = _set;
V[] values = _values;
// Temporarily disable compaction. This is a fix for bug #1738760
tempDisableAutoCompaction();
try {
for (int i = keys.length; i-- > 0;) {
if (keys[i] != FREE
&& keys[i] != REMOVED
&& !procedure.execute((K) keys[i], values[i])) {
removeAt(i);
modified = true;
}
}
} finally {
reenableAutoCompaction(true);
}
return modified;
}
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues(TObjectFunction<V, V> function) {
V[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if (set[i] != FREE && set[i] != REMOVED) {
values[i] = function.execute(values[i]);
}
}
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
protected void rehash(int newCapacity) {
int oldCapacity = _set.length;
int oldSize = size();
Object oldKeys[] = _set;
V oldVals[] = _values;
_set = new Object[newCapacity];
Arrays.fill(_set, FREE);
_values = (V[]) new Object[newCapacity];
// Process entries from the old array, skipping free and removed slots. Put the
// values into the appropriate place in the new array.
int count = 0;
for (int i = oldCapacity; i-- > 0;) {
Object o = oldKeys[i];
if (o == FREE || o == REMOVED) continue;
int index = insertKey((K) o);
if (index < 0) {
throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldKeys);
}
_values[index] = oldVals[i];
//
count++;
}
// Last check: size before and after should be the same
reportPotentialConcurrentMod(size(), oldSize);
}
/**
* retrieves the value for <tt>key</tt>
*
* @param key an <code>Object</code> value
* @return the value of <tt>key</tt> or null if no such mapping exists.
*/
@SuppressWarnings({"unchecked"})
public V get(Object key) {
int index = index(key);
return index < 0 ? null : _values[index];
}
/**
* Empties the map.
*/
public void clear() {
if (size() == 0) {
return; // optimization
}
super.clear();
Arrays.fill(_set, 0, _set.length, FREE);
Arrays.fill(_values, 0, _values.length, null);
}
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>Object</code> value
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public V remove(Object key) {
V prev = null;
int index = index(key);
if (index >= 0) {
prev = _values[index];
removeAt(index); // clear key,state; adjust size
}
return prev;
}
/**
* removes the mapping at <tt>index</tt> from the map.
*
* @param index an <code>int</code> value
*/
public void removeAt(int index) {
_values[index] = null;
super.removeAt(index); // clear key, state; adjust size
}
/**
* Returns a view on the values of the map.
*
* @return a <code>Collection</code> value
*/
public Collection<V> values() {
return new ValueView();
}
/**
* returns a Set view on the keys of the map.
*
* @return a <code>Set</code> value
*/
public Set<K> keySet() {
return new KeyView();
}
/**
* Returns a Set view on the entries of the map.
*
* @return a <code>Set</code> value
*/
public Set<Map.Entry<K, V>> entrySet() {
return new EntryView();
}
/**
* checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue(Object val) {
Object[] set = _set;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if (null == val) {
for (int i = vals.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
val == vals[i]) {
return true;
}
}
} else {
for (int i = vals.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
(val == vals[i] || equals(val, vals[i]))) {
return true;
}
}
} // end of else
return false;
}
/**
* checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey(Object key) {
//noinspection unchecked
return contains(key);
}
/**
* copies the key/value mappings in <tt>map</tt> into this map.
*
* @param map a <code>Map</code> value
*/
public void putAll(Map<? extends K, ? extends V> map) {
ensureCapacity(map.size());
// could optimize this for cases when map instanceof THashMap
for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
}
/**
* a view onto the values of the map.
*/
protected class ValueView extends MapBackedView<V> {
@SuppressWarnings({"unchecked"})
public Iterator<V> iterator() {
return new TObjectHashIterator(THashMap.this) {
protected V objectAtIndex(int index) {
return _values[index];
}
};
}
public boolean containsElement(V value) {
return containsValue(value);
}
public boolean removeElement(V value) {
Object[] values = _values;
Object[] set = _set;
for (int i = values.length; i-- > 0;) {
if ((set[i] != FREE && set[i] != REMOVED) &&
value == values[i] ||
(null != values[i] && THashMap.this.equals(values[i], value))) {
removeAt(i);
return true;
}
}
return false;
}
}
/**
* a view onto the entries of the map.
*/
protected class EntryView extends MapBackedView<Map.Entry<K, V>> {
private final class EntryIterator extends TObjectHashIterator {
EntryIterator(THashMap<K, V> map) {
super(map);
}
@SuppressWarnings({"unchecked"})
public Entry objectAtIndex(final int index) {
return new Entry((K) _set[index], _values[index], index);
}
}
@SuppressWarnings({"unchecked"})
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator(THashMap.this);
}
public boolean removeElement(Map.Entry<K, V> entry) {
if (entry == null) return false;
// have to effectively reimplement Map.remove here
// because we need to return true/false depending on
// whether the removal took place. Since the Entry's
// value can be null, this means that we can't rely
// on the value of the object returned by Map.remove()
// to determine whether a deletion actually happened.
//
// Note also that the deletion is only legal if
// both the key and the value match.
V val;
int index;
K key = keyForEntry(entry);
index = index(key);
if (index >= 0) {
val = valueForEntry(entry);
if (val == _values[index] ||
(null != val && THashMap.this.equals(val, _values[index]))) {
removeAt(index); // clear key,state; adjust size
return true;
}
}
return false;
}
public boolean containsElement(Map.Entry<K, V> entry) {
V val = get(keyForEntry(entry));
V entryValue = entry.getValue();
return entryValue == val ||
(null != val && THashMap.this.equals(val, entryValue));
}
protected V valueForEntry(Map.Entry<K, V> entry) {
return entry.getValue();
}
protected K keyForEntry(Map.Entry<K, V> entry) {
return entry.getKey();
}
}
private abstract class MapBackedView<E> extends AbstractSet<E>
implements Set<E>, Iterable<E> {
public abstract Iterator<E> iterator();
public abstract boolean removeElement(E key);
public abstract boolean containsElement(E key);
@SuppressWarnings({"unchecked"})
public boolean contains(Object key) {
return containsElement((E) key);
}
@SuppressWarnings({"unchecked"})
public boolean remove(Object o) {
try {
return removeElement((E) o);
} catch (ClassCastException ex) {
return false;
}
}
// public boolean containsAll( Collection<?> collection ) {
// for ( Object element : collection ) {
// if ( !contains( element ) ) {
// return false;
// }
// }
// return true;
// }
public void clear() {
THashMap.this.clear();
}
public boolean add(E obj) {
throw new UnsupportedOperationException();
}
public int size() {
return THashMap.this.size();
}
public Object[] toArray() {
Object[] result = new Object[size()];
Iterator<E> e = iterator();
for (int i = 0; e.hasNext(); i++) {
result[i] = e.next();
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size) {
a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
}
Iterator<E> it = iterator();
Object[] result = a;
for (int i = 0; i < size; i++) {
result[i] = it.next();
}
if (a.length > size) {
a[size] = null;
}
return a;
}
public boolean isEmpty() {
return THashMap.this.isEmpty();
}
public boolean addAll(Collection<? extends E> collection) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll(Collection<?> collection) {
boolean changed = false;
Iterator<E> i = iterator();
while (i.hasNext()) {
if (!collection.contains(i.next())) {
i.remove();
changed = true;
}
}
return changed;
}
public String toString() {
Iterator<E> i = iterator();
if (!i.hasNext()) return "{}";
StringBuilder sb = new StringBuilder();
sb.append('{');
for (; ;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (!i.hasNext()) return sb.append('}').toString();
sb.append(", ");
}
}
}
/**
* a view onto the keys of the map.
*/
protected class KeyView extends MapBackedView<K> {
@SuppressWarnings({"unchecked"})
public Iterator<K> iterator() {
return new TObjectHashIterator<K>(THashMap.this);
}
public boolean removeElement(K key) {
return null != THashMap.this.remove(key);
}
public boolean containsElement(K key) {
return THashMap.this.contains(key);
}
}
final class Entry implements Map.Entry<K, V> {
private K key;
private V val;
private final int index;
Entry(final K key, V value, final int index) {
this.key = key;
this.val = value;
this.index = index;
}
public K getKey() {
return key;
}
public V getValue() {
return val;
}
public V setValue(V o) {
if (_values[index] != val) {
throw new ConcurrentModificationException();
}
// need to return previous value
V retval = val;
// update this entry's value, in case setValue is called again
_values[index] = o;
val = o;
return retval;
}
public boolean equals(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<K, V> e1 = this;
Map.Entry e2 = (Map.Entry) o;
return (THashMap.this.equals(e1.getKey(), e2.getKey()))
&& (THashMap.this.equals(e1.getValue(), e1.getValue()));
}
return false;
}
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return key + "=" + val;
}
}
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(1);
// NOTE: Super was not written in version 0
super.writeExternal(out);
// NUMBER OF ENTRIES
out.writeInt(_size);
// ENTRIES
for (int i = _set.length; i-- > 0;) {
if (_set[i] != REMOVED && _set[i] != FREE) {
out.writeObject(_set[i]);
out.writeObject(_values[i]);
}
}
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
byte version = in.readByte();
// NOTE: super was not written in version 0
if (version != 0) {
super.readExternal(in);
}
// NUMBER OF ENTRIES
int size = in.readInt();
setUp(size);
// ENTRIES
while (size-- > 0) {
//noinspection unchecked
K key = (K) in.readObject();
//noinspection unchecked
V val = (V) in.readObject();
put(key, val);
}
}
} // THashMap
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/hash/THashMap.java | Java | asf20 | 26,386 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.function.TObjectFunction;
import gnu.trove.procedure.TObjectObjectProcedure;
import gnu.trove.procedure.TObjectProcedure;
import java.util.Map;
/**
* Interface extension to {@link Map} which adds Trove-specific features.
*/
public interface TMap<K,V> extends Map<K,V> {
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or {@code null} if none was found.
*/
public V putIfAbsent(K key, V value);
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey(TObjectProcedure<? super K> procedure);
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue(TObjectProcedure<? super V> procedure);
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TObjectObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachEntry(TObjectObjectProcedure<? super K, ? super V> procedure);
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
@SuppressWarnings({"unchecked"})
public boolean retainEntries(TObjectObjectProcedure<? super K, ? super V> procedure);
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues(TObjectFunction<V, V> function);
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TMap.java | Java | asf20 | 3,341 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.TLongCollection;
import gnu.trove.function.TLongFunction;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.procedure.TObjectLongProcedure;
import gnu.trove.iterator.TObjectLongIterator;
import java.util.Map;
import java.util.Set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of Object keys and long values.
*/
public interface TObjectLongMap<K> {
// Query Operations
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
long getNoEntryValue();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( Object key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==no_entry_value ? v==no_entry_value : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*<p/>
* Note that no_entry_value is the result of {@link #getNoEntryValue()} and represents
* null for this map instance.
*
* @param value <tt>long</tt> value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( long value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>long</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
long get( Object key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(Object) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryValue()
*/
long put( K key, long value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>long</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
long putIfAbsent( K key, long value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>long</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
long remove( Object key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(Object,long) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends K, ? extends Long> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TObjectLongMap<? extends K> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
Set<K> keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
Object[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
K[] keys( K[] array );
/**
* Returns a {@link TLongCollection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>TLongIterator.remove</tt>,
* <tt>TLongCollection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>long</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>long</tt> values.
*/
long[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>long</tt> values.
*/
long[] values( long[] array );
/**
* Returns a <tt>TObjectLongIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TObjectLongIterator</tt> with access to this map's keys and values.
*/
public TObjectLongIterator<K> iterator();
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( K key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( K key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( K key, long adjust_amount, long put_amount );
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TObjectLongProcedure<? super K> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectLongProcedure<? super K> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TObjectLongMap.java | Java | asf20 | 18,342 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.function.TObjectFunction;
import gnu.trove.set.TIntSet;
import java.util.Collection;
import java.util.Map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of int keys and Object values.
*/
public interface TIntObjectMap<V> {
// Query Operations
/**
* Returns the value that represents null in the {@link #keySet()}.
* The default value is generally zero, but can be changed during
* construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
int getNoEntryKey();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>key.equals(k)</tt>. (There can be at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( int key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*
* @param value value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( Object value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>int</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
V get( int key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(int) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryKey()
*/
V put( int key, V value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or null
* if none was found.
*/
V putIfAbsent( int key, V value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>key.equals(k)</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>int</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
V remove( int key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(int,Object) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends Integer, ? extends V> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TIntObjectMap<? extends V> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link TIntSet} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
TIntSet keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
int[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
int[] keys( int[] array );
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
Collection<V> valueCollection();
/**
* Returns the values of the map as an array of <tt>int</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>int</tt> values.
*/
V[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>int</tt> values.
*/
V[] values( V[] array );
/**
* Returns a <tt>TIntObjectIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TIntObjectIterator</tt> with access to this map's keys and values.
*/
public TIntObjectIterator<V> iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TObjectProcedure<? super V> procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TIntObjectProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntObjectProcedure<? super V> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TObjectFunction</code> value
*/
public void transformValues( TObjectFunction<V,V> function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntObjectProcedure<? super V> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TIntObjectMap.java | Java | asf20 | 16,899 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.iterator.*;
import gnu.trove.procedure.*;
import gnu.trove.set.*;
import gnu.trove.TLongCollection;
import java.util.Map;
import java.io.Serializable;
/**
* Interface for a primitive map of int keys and long values.
*/
public interface TIntLongMap {
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null key in this collection.
*/
public int getNoEntryKey();
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
public long getNoEntryValue();
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>int</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long put( int key, long value );
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key an <code>int</code> value
* @param value an <code>long</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long putIfAbsent( int key, long value );
/**
* Put all the entries from the given Map into this map.
*
* @param map The Map from which entries will be obtained to put into this map.
*/
public void putAll( Map<? extends Integer, ? extends Long> map );
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
public void putAll( TIntLongMap map );
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long get( int key );
/**
* Empties the map.
*/
public void clear();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
public boolean isEmpty();
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>int</code> value
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
public long remove( int key );
/**
* Returns an <tt>int</tt> value that is the number of elements in the map.
*
* @return an <tt>int</tt> value that is the number of elements in the map.
*/
public int size();
/**
* Returns the keys of the map as a <tt>TIntSet</tt>
*
* @return the keys of the map as a <tt>TIntSet</tt>
*/
public TIntSet keySet();
/**
* Returns the keys of the map as an array of <tt>int</tt> values.
*
* @return the keys of the map as an array of <tt>int</tt> values.
*/
public int[] keys();
/**
* Returns the keys of the map.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
public int[] keys( int[] array );
/**
* Returns the values of the map as a <tt>TLongCollection</tt>
*
* @return the values of the map as a <tt>TLongCollection</tt>
*/
public TLongCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>#e#</tt> values.
*
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values();
/**
* Returns the values of the map using an existing array.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>#e#</tt> values.
*/
public long[] values( long[] array );
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( long val );
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( int key );
/**
* @return a TIntLongIterator with access to this map's keys and values
*/
public TIntLongIterator iterator();
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>T#F#Procedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TLongProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOIntLongProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TIntLongProcedure procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TIntLongProcedure procedure );
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( int key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( int key, long amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public long adjustOrPutValue( int key, long adjust_amount, long put_amount );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TIntLongMap.java | Java | asf20 | 9,262 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.map;
import gnu.trove.TIntCollection;
import gnu.trove.function.TIntFunction;
import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.procedure.TObjectIntProcedure;
import gnu.trove.iterator.TObjectIntIterator;
import java.util.Map;
import java.util.Set;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for a primitive map of Object keys and int values.
*/
public interface TObjectIntMap<K> {
// Query Operations
/**
* Returns the value that will be returned from {@link #get} or {@link #put} if no
* entry exists for a given key. The default value is generally zero, but can be
* changed during construction of the collection.
*
* @return the value that represents a null value in this collection.
*/
int getNoEntryValue();
/**
* Returns the number of key-value mappings in this map. If the
* map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of key-value mappings in this map
*/
int size();
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key. More formally, returns <tt>true</tt> if and only if
* this map contains a mapping for a key <tt>k</tt> such that
* <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
* at most one such mapping.)
*
* @param key key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
boolean containsKey( Object key );
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value. More formally, returns <tt>true</tt> if and only if
* this map contains at least one mapping to a value <tt>v</tt> such that
* <tt>(value==no_entry_value ? v==no_entry_value : value.equals(v))</tt>. This operation
* will probably require time linear in the map size for most
* implementations of the <tt>Map</tt> interface.
*<p/>
* Note that no_entry_value is the result of {@link #getNoEntryValue()} and represents
* null for this map instance.
*
* @param value <tt>int</tt> value whose presence in this map is to be tested
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value
* @throws ClassCastException if the value is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified value is null and this
* map does not permit null values (optional)
*/
boolean containsValue( int value );
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @param key the key whose associated value is to be returned
* @return the <tt>int</tt> value to which the specified key is mapped, or
* {@code null} if this map contains no mapping for the key
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this map
* does not permit null keys (optional)
*/
int get( Object key );
// Modification Operations
/**
* Associates the specified value with the specified key in this map
* (optional operation). If the map previously contained a mapping for
* the key, the old value is replaced by the specified value. (A map
* <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
* if {@link #containsKey(Object) m.containsKey(k)} would return
* <tt>true</tt>.)
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>no_entry_value</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>no_entry_value</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>,
* if the implementation supports <tt>null</tt> values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* @throws NullPointerException if the specified key or value is null
* and this map does not permit null keys or values
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* @see #getNoEntryValue()
*/
int put( K key, int value);
/**
* Inserts a key/value pair into the map if the specified key is not already
* associated with a value.
*
* @param key key with which the specified value is to be associated
* @param value an <tt>int</tt> value to be associated with the specified key
*
* @return the previous value associated with <tt>key</tt>, or the "no entry" value
* if none was found (see {@link #getNoEntryValue}).
*/
int putIfAbsent( K key, int value );
/**
* Removes the mapping for a key from this map if it is present
* (optional operation). More formally, if this map contains a mapping
* from key <tt>k</tt> to value <tt>v</tt> such that
* <code>(key==null ? k==null : key.equals(k))</code>, that mapping
* is removed. (The map can contain at most one such mapping.)
*
* <p>Returns the value to which this map previously associated the key,
* or <tt>null</tt> if the map contained no mapping for the key.
*
* <p>If this map permits null values, then a return value of
* <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contained no mapping for the key; it's also possible that the map
* explicitly mapped the key to <tt>null</tt>.
*
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key whose mapping is to be removed from the map
* @return the previous <tt>int</tt> value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this map
* @throws ClassCastException if the key is of an inappropriate type for
* this map (optional)
* @throws NullPointerException if the specified key is null and this
* map does not permit null keys (optional)
*/
int remove( Object key );
// Bulk Operations
/**
* Copies all of the mappings from the specified map to this map
* (optional operation). The effect of this call is equivalent to that
* of calling {@link #put(Object,int) put(k, v)} on this map once
* for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
* specified map. The behavior of this operation is undefined if the
* specified map is modified while the operation is in progress.
*
* @param m mappings to be stored in this map
* @throws UnsupportedOperationException if the <tt>putAll</tt> operation
* is not supported by this map
* @throws ClassCastException if the class of a key or value in the
* specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null, or if
* this map does not permit null keys or values, and the
* specified map contains null keys or values
* @throws IllegalArgumentException if some property of a key or value in
* the specified map prevents it from being stored in this map
*/
void putAll( Map<? extends K, ? extends Integer> m);
/**
* Put all the entries from the given map into this map.
*
* @param map The map from which entries will be obtained to put into this map.
*/
void putAll( TObjectIntMap<? extends K> map );
/**
* Removes all of the mappings from this map (optional operation).
* The map will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this map
*/
void clear();
// Views
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @return a set view of the keys contained in this map
*/
Set<K> keySet();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @return a copy of the keys of the map as an array.
*/
Object[] keys();
/**
* Returns a copy of the keys of the map as an array.
* Changes to the array of keys will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the keys of the map as an array.
*/
K[] keys( K[] array );
/**
* Returns a {@link TIntCollection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the <tt>TIntIterator.remove</tt>,
* <tt>TIntCollection.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
* support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map
*/
TIntCollection valueCollection();
/**
* Returns the values of the map as an array of <tt>int</tt> values.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @return the values of the map as an array of <tt>int</tt> values.
*/
int[] values();
/**
* Returns the values of the map using an existing array.
* Changes to the array of values will not be reflected in the map
* nor vice-versa.
*
* @param array the array into which the elements of the list are to be stored,
* if it is big enough; otherwise, a new array of the same type is
* allocated for this purpose.
* @return the values of the map as an array of <tt>int</tt> values.
*/
int[] values( int[] array );
/**
* Returns a <tt>TObjectIntIterator</tt> with access to this map's keys and values.
*
* @return a <tt>TObjectIntIterator</tt> with access to this map's keys and values.
*/
public TObjectIntIterator<K> iterator();
/**
* Increments the primitive value mapped to key by 1
*
* @param key the key of the value to increment
* @return true if a mapping was found and modified.
*/
public boolean increment( K key );
/**
* Adjusts the primitive value mapped to key.
*
* @param key the key of the value to increment
* @param amount the amount to adjust the value by.
* @return true if a mapping was found and modified.
*/
public boolean adjustValue( K key, int amount );
/**
* Adjusts the primitive value mapped to the key if the key is present in the map.
* Otherwise, the <tt>initial_value</tt> is put in the map.
*
* @param key the key of the value to increment
* @param adjust_amount the amount to adjust the value by
* @param put_amount the value put into the map if the key is not initial present
*
* @return the value present in the map after the adjustment or put operation
*/
public int adjustOrPutValue( K key, int adjust_amount, int put_amount );
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the keys terminated because
* the procedure returned false for some key.
*/
public boolean forEachKey( TObjectProcedure<? super K> procedure );
/**
* Executes <tt>procedure</tt> for each value in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
public boolean forEachValue( TIntProcedure procedure );
/**
* Executes <tt>procedure</tt> for each key/value entry in the
* map.
*
* @param procedure a <code>TOObjectIntProcedure</code> value
* @return false if the loop over the entries terminated because
* the procedure returned false for some entry.
*/
public boolean forEachEntry( TObjectIntProcedure<? super K> procedure );
/**
* Transform the values in this map using <tt>function</tt>.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Retains only those entries in the map for which the procedure
* returns a true value.
*
* @param procedure determines which entries to keep
* @return true if the map was modified.
*/
public boolean retainEntries( TObjectIntProcedure<? super K> procedure );
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals( Object o );
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hash codes of each entry in the map's
* <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
* implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
* <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this map
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/map/TObjectIntMap.java | Java | asf20 | 18,299 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
/**
* Simple class meant as a possible main class (via manifest) to report the
* implementation version of the trove4j jar.
* <p/>
* This may be useful to ask feedback WITH build version information
* <p/>
* The Main-Class entry in the manifest.mf should be set during the build as well
* as the Implementation-Version manifest attribute should be set as well.
* <p/>
* Created by IntelliJ IDEA.
* User: Johan Parent
* Date: 3/03/11
* Time: 22:10
*/
public class Version {
public static void main(String[] args) {
System.out.println(getVersion());
}
/**
* Returns the implementation version of trove4j. Intended for applications
* wanting to return the version of trove4j they are using
* <p/>
* NOTE: this method will only return a useful version when working
* with a trove4j jar as it requires a manifest file
*
* @return
*/
public static String getVersion() {
String version = Version.class.getPackage().getImplementationVersion();
//
if (version != null) {
return "trove4j version " + version;
}
return "Sorry no Implementation-Version manifest attribute available";
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/Version.java | Java | asf20 | 2,357 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.queue;
import gnu.trove.TLongCollection;
import java.io.Serializable;
/**
* Interface for Trove queue implementations.
*
* @see java.util.Queue
*/
public interface TLongQueue extends TLongCollection {
/**
* Retrieves and removes the head of this queue. This method differs from
* {@link #poll} only in that it throws an exception if this queue is empty.
*/
public long element();
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions. When using a
* capacity-restricted queue, this method is generally preferable to
* {@link #add}, which can fail to insert an element only by throwing an exception.
*
* @param e The element to add.
*
* @return <tt>true</tt> if the element was added to this queue, else <tt>false</tt>
*/
public boolean offer( long e );
/**
* Retrieves, but does not remove, the head of this queue, or returns
* {@link #getNoEntryValue} if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public long peek();
/**
* Retrieves and removes the head of this queue, or returns {@link #getNoEntryValue}
* if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public long poll();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/queue/TLongQueue.java | Java | asf20 | 2,326 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.queue;
import gnu.trove.TIntCollection;
import java.io.Serializable;
/**
* Interface for Trove queue implementations.
*
* @see java.util.Queue
*/
public interface TIntQueue extends TIntCollection {
/**
* Retrieves and removes the head of this queue. This method differs from
* {@link #poll} only in that it throws an exception if this queue is empty.
*/
public int element();
/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions. When using a
* capacity-restricted queue, this method is generally preferable to
* {@link #add}, which can fail to insert an element only by throwing an exception.
*
* @param e The element to add.
*
* @return <tt>true</tt> if the element was added to this queue, else <tt>false</tt>
*/
public boolean offer( int e );
/**
* Retrieves, but does not remove, the head of this queue, or returns
* {@link #getNoEntryValue} if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public int peek();
/**
* Retrieves and removes the head of this queue, or returns {@link #getNoEntryValue}
* if this queue is empty.
*
* @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty
*/
public int poll();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/queue/TIntQueue.java | Java | asf20 | 2,319 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import java.io.Serializable;
/**
* A stack of long primitives.
*/
public interface TLongStack {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue();
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>long</code> value
*/
public void push( long val );
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long pop();
/**
* Returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long peek();
/**
* Returns the current depth of the stack.
*/
public int size();
/**
* Clears the stack.
*/
public void clear();
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack.
*
* @return an <code>long[]</code> value
*/
public long[] toArray();
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack.
*
* @param dest the array to copy into.
*/
public void toArray( long[] dest );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/stack/TLongStack.java | Java | asf20 | 2,662 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import java.io.Serializable;
/**
* A stack of int primitives.
*/
public interface TIntStack {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue();
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>int</code> value
*/
public void push( int val );
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int pop();
/**
* Returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int peek();
/**
* Returns the current depth of the stack.
*/
public int size();
/**
* Clears the stack.
*/
public void clear();
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack.
*
* @return an <code>int[]</code> value
*/
public int[] toArray();
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack.
*
* @param dest the array to copy into.
*/
public void toArray( int[] dest );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/stack/TIntStack.java | Java | asf20 | 2,650 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack.array;
import gnu.trove.stack.TIntStack;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A stack of int primitives, backed by a TIntArrayList
*/
public class TIntArrayStack implements TIntStack, Externalizable {
static final long serialVersionUID = 1L;
/** the list used to hold the stack values. */
protected TIntArrayList _list;
public static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/**
* Creates a new <code>TIntArrayStack</code> instance with the default
* capacity.
*/
public TIntArrayStack() {
this( DEFAULT_CAPACITY );
}
/**
* Creates a new <code>TIntArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
*/
public TIntArrayStack( int capacity ) {
_list = new TIntArrayList( capacity );
}
/**
* Creates a new <code>TIntArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
* @param no_entry_value value that represents null
*/
public TIntArrayStack( int capacity, int no_entry_value ) {
_list = new TIntArrayList( capacity, no_entry_value );
}
/**
* Creates a new <code>TIntArrayStack</code> instance that is
* a copy of the instanced passed to us.
*
* @param stack the instance to copy
*/
public TIntArrayStack( TIntStack stack ) {
if ( stack instanceof TIntArrayStack ) {
TIntArrayStack array_stack = ( TIntArrayStack ) stack;
this._list = new TIntArrayList( array_stack._list );
} else {
throw new UnsupportedOperationException( "Only support TIntArrayStack" );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return _list.getNoEntryValue();
}
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>int</code> value
*/
public void push( int val ) {
_list.add( val );
}
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int pop() {
return _list.removeAt( _list.size() - 1 );
}
/**
* Returns the value at the top of the stack.
*
* @return an <code>int</code> value
*/
public int peek() {
return _list.get( _list.size() - 1 );
}
/**
* Returns the current depth of the stack.
*/
public int size() {
return _list.size();
}
/**
* Clears the stack.
*/
public void clear() {
_list.clear();
}
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top of the stack.
*
* @return an <code>int[]</code> value
*/
public int[] toArray() {
int[] retval = _list.toArray();
reverse( retval, 0, size() );
return retval;
}
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top
* of the stack.
* <p>
* If the native array is smaller than the stack depth,
* the native array will be filled with the elements from the top
* of the array until it is full and exclude the remainder.
*
* @param dest the array to copy into.
*/
public void toArray( int[] dest ) {
int size = size();
int start = size - dest.length;
if ( start < 0 ) {
start = 0;
}
int length = Math.min( size, dest.length );
_list.toArray( dest, start, length );
reverse( dest, 0, length );
if ( dest.length > size ) {
dest[size] = _list.getNoEntryValue();
}
}
/**
* Reverse the order of the elements in the range of the list.
*
* @param dest the array of data
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
private void reverse( int[] dest, int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( dest, i, j );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param dest the array of data
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int[] dest, int i, int j ) {
int tmp = dest[ i ];
dest[ i ] = dest[ j ];
dest[ j ] = tmp;
}
/**
* Returns a String representation of the list, top to bottom.
*
* @return a <code>String</code> value
*/
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = _list.size() - 1; i > 0; i-- ) {
buf.append( _list.get( i ) );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _list.get( 0 ) );
}
buf.append( "}" );
return buf.toString();
}
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
TIntArrayStack that = ( TIntArrayStack ) o;
return _list.equals( that._list );
}
public int hashCode() {
return _list.hashCode();
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LIST
out.writeObject( _list );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LIST
_list = ( TIntArrayList ) in.readObject();
}
} // TIntArrayStack
| 04146814d-23 | SimpleTrove/src/gnu/trove/stack/array/TIntArrayStack.java | Java | asf20 | 7,763 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.stack.array;
import gnu.trove.stack.TLongStack;
import gnu.trove.list.array.TLongArrayList;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A stack of long primitives, backed by a TLongArrayList
*/
public class TLongArrayStack implements TLongStack, Externalizable {
static final long serialVersionUID = 1L;
/** the list used to hold the stack values. */
protected TLongArrayList _list;
public static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/**
* Creates a new <code>TLongArrayStack</code> instance with the default
* capacity.
*/
public TLongArrayStack() {
this( DEFAULT_CAPACITY );
}
/**
* Creates a new <code>TLongArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
*/
public TLongArrayStack( int capacity ) {
_list = new TLongArrayList( capacity );
}
/**
* Creates a new <code>TLongArrayStack</code> instance with the
* specified capacity.
*
* @param capacity the initial depth of the stack
* @param no_entry_value value that represents null
*/
public TLongArrayStack( int capacity, long no_entry_value ) {
_list = new TLongArrayList( capacity, no_entry_value );
}
/**
* Creates a new <code>TLongArrayStack</code> instance that is
* a copy of the instanced passed to us.
*
* @param stack the instance to copy
*/
public TLongArrayStack( TLongStack stack ) {
if ( stack instanceof TLongArrayStack ) {
TLongArrayStack array_stack = ( TLongArrayStack ) stack;
this._list = new TLongArrayList( array_stack._list );
} else {
throw new UnsupportedOperationException( "Only support TLongArrayStack" );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return _list.getNoEntryValue();
}
/**
* Pushes the value onto the top of the stack.
*
* @param val an <code>long</code> value
*/
public void push( long val ) {
_list.add( val );
}
/**
* Removes and returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long pop() {
return _list.removeAt( _list.size() - 1 );
}
/**
* Returns the value at the top of the stack.
*
* @return an <code>long</code> value
*/
public long peek() {
return _list.get( _list.size() - 1 );
}
/**
* Returns the current depth of the stack.
*/
public int size() {
return _list.size();
}
/**
* Clears the stack.
*/
public void clear() {
_list.clear();
}
/**
* Copies the contents of the stack into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top of the stack.
*
* @return an <code>long[]</code> value
*/
public long[] toArray() {
long[] retval = _list.toArray();
reverse( retval, 0, size() );
return retval;
}
/**
* Copies a slice of the list into a native array. Note that this will NOT
* pop them out of the stack. The front of the list will be the top
* of the stack.
* <p>
* If the native array is smaller than the stack depth,
* the native array will be filled with the elements from the top
* of the array until it is full and exclude the remainder.
*
* @param dest the array to copy into.
*/
public void toArray( long[] dest ) {
int size = size();
int start = size - dest.length;
if ( start < 0 ) {
start = 0;
}
int length = Math.min( size, dest.length );
_list.toArray( dest, start, length );
reverse( dest, 0, length );
if ( dest.length > size ) {
dest[size] = _list.getNoEntryValue();
}
}
/**
* Reverse the order of the elements in the range of the list.
*
* @param dest the array of data
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
private void reverse( long[] dest, int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( dest, i, j );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param dest the array of data
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( long[] dest, int i, int j ) {
long tmp = dest[ i ];
dest[ i ] = dest[ j ];
dest[ j ] = tmp;
}
/**
* Returns a String representation of the list, top to bottom.
*
* @return a <code>String</code> value
*/
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = _list.size() - 1; i > 0; i-- ) {
buf.append( _list.get( i ) );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _list.get( 0 ) );
}
buf.append( "}" );
return buf.toString();
}
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
TLongArrayStack that = ( TLongArrayStack ) o;
return _list.equals( that._list );
}
public int hashCode() {
return _list.hashCode();
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LIST
out.writeObject( _list );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LIST
_list = ( TLongArrayList ) in.readObject();
}
} // TLongArrayStack
| 04146814d-23 | SimpleTrove/src/gnu/trove/stack/array/TLongArrayStack.java | Java | asf20 | 7,805 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2002, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.strategy;
import java.io.Serializable;
/**
* Interface to support pluggable hashing strategies in maps and sets.
* Implementers can use this interface to make the trove hashing
* algorithms use object values, values provided by the java runtime,
* or a custom strategy when computing hashcodes.
*
* @author Eric Friedman
* @author Rob Eden
*/
public interface HashingStrategy<T> extends Serializable {
static final long serialVersionUID = 5674097166776615540L;
/**
* Computes a hash code for the specified object. Implementers
* can use the object's own <tt>hashCode</tt> method, the Java
* runtime's <tt>identityHashCode</tt>, or a custom scheme.
*
* @param object for which the hashcode is to be computed
* @return the hashCode
*/
int computeHashCode( T object );
/**
* Compares o1 and o2 for equality. Strategy implementers may use
* the objects' own equals() methods, compare object references,
* or implement some custom scheme.
*
* @param o1 an <code>Object</code> value
* @param o2 an <code>Object</code> value
* @return true if the objects are equal according to this strategy.
*/
boolean equals( T o1, T o2 );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/strategy/HashingStrategy.java | Java | asf20 | 2,146 |
package gnu.trove.strategy;
/**
* A {@link gnu.trove.strategy.HashingStrategy} that does identity comparisons
* (<tt>==</tt>) and uses {@link System#identityHashCode(Object)} for hashCode generation.
*/
public class IdentityHashingStrategy<K> implements HashingStrategy<K> {
static final long serialVersionUID = -5188534454583764904L;
public int computeHashCode( K object ) {
return System.identityHashCode( object );
}
public boolean equals( K o1, K o2 ) {
return o1 == o2;
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/strategy/IdentityHashingStrategy.java | Java | asf20 | 512 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and long.
*/
public interface TLongLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, long b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TLongLongProcedure.java | Java | asf20 | 1,665 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and int.
*/
public interface TLongIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, int b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TLongIntProcedure.java | Java | asf20 | 1,661 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and long.
*/
public interface TIntLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, long b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TIntLongProcedure.java | Java | asf20 | 1,661 |