HashSet – Internal Working


HashSet newSet = new HashSet();


newSet.add(new String(“Google”));

Print : newSet.size()  — returns 1 .   Lets see why it returns 1 and not 2


  • HashSet internally uses HashMap for storing values
  • HashSet does not guarantee  insertion order
  • HashSet allows null values
  • Does not allow duplicate values
  • When value is added to HashSet the following  happens  internally
    • The values are stored as Key to the HashMap
    • Dummy object is created and stored as value in the HashMap. Note HashMap allows duplicate values
  • Refer to understand how the above code returns 1
  • Iterators are used for retrieving the values as it does  not have a getter method of its own
  • HashSet creation internally creates a HashMap of initial capacity 16 and load factor 0.75
  • If storing custom objects, then make sure to overwrite equals() and hashCode() as they are stored as key in HashMap internally
  • HashSet internally uses only shallow Copy
  • No get(Object o) is available as the data is stored internally in a MAP as key .  It only supports Contains method
  • O(1) for add, remove,contains and size provided hashing is handled properly
  • It is not synchronized.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Cheat Sheet To JAVA Latest Technology

%d bloggers like this: