Exploring Java Collections – Understanding HashSets

Exploring Java Fundamentals - Understanding HashSet

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)

Example:

wp-content/uploads/2022/05/hashset.png

Output:

true
true
false

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.

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *