• Posted one year ago
A HashSet is a type of Set and implements the Set interface from the java.util.AbstractSet package. It internally uses a HashTable (which intern uses a HashMap), and accepts only unique elements in the set. It neither guarantees the iteration order of the set nor that the order will remain unchanged over the period of time. It also permits the null value to be inserted.
- HashSet is implementation of the java.util.Set interface.
- HashSet does not allow us to store duplicate elements in java.
- HashSet Internally uses HashMap key for making uniqueness.
- Its initial capacity is 16. And load factor is 0.75.
- HashSet will return in random order. We can’t expect same order all the times.
- Set will not maintain indexing .
Constructors in HashSet:
- HashSet() Default initial capacity is 16 and default load factor is 0.75.
- HashSet(int initialCapacity) default loadFactor of 0.75
- HashSet(int initialCapacity, float loadFactor)
- new HashSet(Collection C)
Features of HashSet:-
- Duplicate elements - HashSet does not allows to store duplicate elements in java.
- Null elements - One null element can be added in HashSet in java.
- Insertion order - HashSet does not maintains insertion order in java.
- Asynchronous - HashSet is not synchronized (because 2 threads on same HashSet object can access it at same time) in java.
- Performance - HashSet is not synchronized, hence its operations are faster as compared to some other synchronized implementation of Set interface in java.