HashSet Tutorial: HashSet implements the Set interface. HashSet uses hash table, at the background, for storage of elements; uses a mechanism called hashing. No guarantee of returning the elements in the same order when called different times or insertion order. HashSet permits null element. But the set should contain only one null value as duplicates are not permitted. The methods of HashSet are not synchronized. But a synchronized version of HashSet can be obtained.
HashSet hs1 = new HashSet();
Set mySet = Collections.synchronizedSet(hs1);
Now mySet methods are synchronized. But still hs1 is not synchronized.
Following is the class signature:
public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
Following are the constructors
- HashSet(): Creates a HashSet object without any elements initially. The initial capacity is 10 and load factor 0.75.
- HashSet(int iniCap): Creates a HashSet object without any elements initially. The initial capacity is iniCap and load factor 0.75. This increases performance, but the required capacity should be known early.
- HashSet(int iniCap, float lf): Creates a HashSet object without any elements initially. The initial capacity is iniCap with load factor lf.
- HashSet(Collection col): Creates a HashSet object with the elements of col. That is, other collection class elements can be added at the time of object creation itself. The initial capacity is equal to the number of elements of col. The load factor is 0.75.
Load factor is the increment value of hash table when the existing capacity is exhausted. It is 0.75 over the existing capacity.
HashSet can make use of the methods of Collection interface as it is derived from Collection. It adds the following method.
- Object clone(): Returns a cloned HashSet object containing the same elements of the original HashSet.
HashSet Tutorial: Two programs are given on HashSet with different functionality.
- HashSet General: In this program, the general methods like contains, equals, add, size, remove, toArray and hashCode usage is illustrated. Elements are printed with foreach loop.
- HashSet Operations: Iterator for printing the elements of HashSet is used. Methods like addAll, clear, retainAll, containsAll and toString are used. Two generics hash sets are created.