Card image cap

Exploring Java Collections - Understanding HashSets

Java Concepts  • 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.

  1. HashSet is implementation of the java.util.Set interface.
  2. HashSet does not allow us to store duplicate elements in java.
  3. HashSet Internally uses HashMap key for making uniqueness.
  4. Its initial capacity is 16. And load factor is 0.75.
  5. HashSet will return in random order. We can’t expect same order all the times.
  6. 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.

Enjoying my posts?
You can now show me your support! 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept