How to use HashSet in Java?

HashSet :

HashSet implements Set interface. To store the values it uses Hashtable internally which uses hashing mechanism. Because of Hashing there are two advantages, first because it is used to find duplicates using the key and second is it gives constant time performance for operations such as add, remove, contains etc.

Lets look at some characteristics for HashSet
1. HashSet allows null value.
2. HashSet is not synchronized.
3. Order of elements may or may not remain same.

Creating a HashSet :

HashSet provides four sets of constructors :

public HashSet()
public HashSet( int initialCapacity )
public HashSet( int initialCapacity, int loadFactor )

It also provides constructor which take argument as Collection which is useful to convert Collection such as TreeSet to HashSet.

public HashSet( Collection collec )

But changing collection to HashSet we need to understand that if Collection have duplicate elements then only one will be reflected in the HashSet.

Its good practice to have local variable to have its interface type.

Set hashSet = new HashSet();

Now lets look how HashSet is used to find duplicate elements. HashSet provides add method which returns true when element gets added if it found duplicate element and fail to add that element to the HashSet then it returns as false.

Set set = new HashSet();
if (!set.add("One")) {
System.out.println("Duplicate Found");
} else {
System.out.println("Added successfully ");
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment