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.
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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.