Design a site like this with WordPress.com
Get started

HashSet

Hashset as the name suggests is an implementation of the set interface. A set does not allow duplicates in the collection. if you try to insert the same object twice, the already existing is replaced. This collection does not guarantee of the insertion order and the objects will not be returned in any particular order

A HashSet depends on the hash function of the object and is backed by a hashmap. So a hashset similar to the hashmap depends heavily on the hashcode and equals method to implement its functionality.

A HashSet is not synchronized, it means that there is no guarantee of the consistency of the objects in the HashSet if they are accessed/modified by multiple threads.

 Set<String> nameSet = new HashSet<>();
       nameSet.add(null);
       nameSet.add("Jane");
       nameSet.add("polly");
       nameSet.add("Jane");
       nameSet.add(null);
       System.out.println(nameSet);

[null, polly, Jane]

As from the example it is clear that there is no particular order in which the elements retrieved. A null is also allowed to be inserted into the collection.

The HashSet is best for search operations if the hashcode function is designed so that there are minimum hash collisions. It is also advisable to initialize the Set with capacity if you know size it before hand.

As stated earlier a HashSet is backed by a HashMap, so all the elements are added as keys in the map and all the values are defaulted to a dummy element.

Below is representation of the add method in the HashSet. The add method adds element as key in the map and value is defaulted to a dummy value.

private static final Object PRESENT = new Object();
 public boolean add(E e) {
        return map.put(e, PRESENT)==null;
 }

Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: