Saturday, June 23, 2012

HashSet in Java – 10 Examples Programs Tutorial

HashSet in Java is a collection which implements Set interface and backed by an HashMap. Since HashSet uses HashMap internally it provides constant time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order. Iterator of HashSet is fail-fast and throws ConcurrentModificationException if HashSet instance is modified concurrently during iteration by using any method other than remove() method of iterator class.If you want to keep insertion order by using HashSet than consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short correct understanding of HashSet is must for any Java developer.


Java HashSet Examples TutorialsIn this Java tutorial we will learn various examples of HashSet in Java and how to perform different operations in HashSet with simple examples. There is also a very famous interview questions based on HashSet is difference between HashMap and HashSet in java, which we have discussed in earlier post. You can also look that to learn more about HashSet in Java.

How to create HashSet object in Java
Creating HashSet is not different than any other Collection class. HashSet provides multiple constructor which gives you flexibility to create HashSet either copying objects from another collection, an standard way to convert ArrayList to HashSet. You can also specify initialCapacity and load factor to prevent unnecessary resizing of HashSet.

HashSet assetSet = new HashSet(); //HashSet instance without any element
HashSet fromArrayList = new HashSet(Arrays.asList(“Java”,”C++”)); //copying content
HashSet properSet = new HashSet(50); //HashSet with initial capacity


How to store Object into HashSet
Storing object into HashSet, also called elements is similar to Other implementation of Set, add() method of Set interface is used to store object into HashSet. Since Set doesn’t allow duplicates if HashSet already contains that object, it will not change the HashSet and add() will return false in that case.

assetSet.add("I am first object in HashSet"); // add will return true
assetSet.add("I am first object in HashSet"); // add will return false as Set already has


How to check HashSet is empty
There are multiple ways to check if HashSet is empty. An HashSet is called empty if it does not contain any element or if its size is zero. You can get size of HashSet as shown in further example and than see if its zero or not. Another way to do is by using isEmpty() method which returns true if underlying Collection or HashSet is empty.

boolean isEmpty = assetSet.isEmpty(); //isEmpty() will return true if HashSet is empty

if(assetSet.size() == 0){
    System.out.println("HashSet is empty, does not contain any element");
}

How to remove objects from HashSet in Java
HashSet in Java has nice little utility method called remove() remove object from HashSet. remove() deletes the specified object or element from this Set and returns true if Set contains element or false if Set does not contain that element. You can also use Iterator’s remove method for deleting object while Iterating over it.

assetSet.remove("I am first object in HashSet"); // remove will return true
assetSet.remove("I am first object in HashSet"); // remove will return false now

Iterator setIterator = assetSet.iterator()
while(setIterator.hasNext()){
   String item = setIterator().next();
   setIterator.remove(); //removes current element
}


How to clear HashSet in Java
HashSet in Java has a clear() method which removes all elements from HashSet and by clearing HashSet you can reuse It, only problem is that during multi-threading you need to be extra careful because while one thread is clearing objects form HashSet other thread can iterate over it.

assetSet.clear(); //clear Set, size of Set will be zero now

How to find size of HashSet in java
Size of HashSet returns number of objects stored in Collection. You can find size of HashSet by calling size() method of HashSet in Java. For an empty HashSet size() will return zero.

int size = assetSet.size(); // count of object stored in HashSet


How to check if HashSet contains an object
checking existence of an object inside HashSet in Java is not difficult, HashSet provides a utility method contains(Object o) for very same purpose. contains returns true if object exists in collection otherwise it returns false. By the way contains() method uses equals method to compare two object in HashSet. That’s why its important to override hashCode and equals method in Java.

assetSet.contains("Does this object exists in HashSet"); //contains() will return false
assetSet.add("Does this object exists in HashSet"); //add will return true as its new object
assetSet.contains("Does this object exists in HashSet"); // now contains will return true

How to convert HashSet into array in Java
HashSet has an utility method called toArray() inherited from Set interface. which is used to convert a HashSet into Array in Java see following example of converting hashset into array. toArray() returns an object array.

Object[] hashsetArray = assetSet.toArray();
Set
<String> stringSet = new HashSet<String>();
String
[] strArray = stringSet.toArray();

After Java 1.5 this method accept generics parameter and It can return the same type of element which is stored in HashSet. If size of Array is not sufficient than a new Array with runtime type of elements in HashSet is created. If you want to convert HashSet into Array List than search on Javarevisited.


That's all on this Java HashSet tutorial. HashSet in java is a one of the frequently used Collection class and can be very useful on certain scenario where you need to store unique elements with quick retrieval. important point to not about java HashSet it that add, remove, contains() and size() is constant time operation.

Other Java tutorial on collection framework:

3 comments :

Anonymous said...

Which one is faster between HashSet and ArrayList ?

Anonymous said...

sir,
can you tell me how HshSet works internally.

there is no key for store it in a bucket
then how HashSet store element internally..

Venkys said...

While you might have great capabilities, and knowledge of Java per se, unfortunate as it is, I am unable to connect your thought process (as regards to the data structures in computer science) into logical statements as explained.

Can you kindly do something about this in a way that the thoughts flow freely from a good teacher like you (who has a good grasp but...)

Thanks in advance...

Post a Comment