HashSet in Java is a collection that implements the Set interface and is backed by a 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.
Also, Iterator of HashSet is fail-fast and throws ConcurrentModificationException if the HashSet instance is modified concurrently during iteration by using any method other than the remove() method of iterator class.
If you want to keep insertion order by using HashSet then consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short, a correct understanding of HashSet is a must for any Java developer.
If you want to keep insertion order by using HashSet then consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short, a correct understanding of HashSet is a must for any Java developer.
10 Example of HashSet in Java
In 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 question based on HashSet is the difference between HashMap and HashSet in java, which we have discussed in an earlier post. You can also look that to learn more about HashSet in Java.
1. How to create HashSet object in Java
Creating HashSet is not different than any other Collection class. HashSet provides multiple constructors which give you the flexibility to create HashSet either copying objects from another collection, a 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
HashSet fromArrayList = new HashSet(Arrays.asList(“Java”,”C++”)); //copying content
HashSet properSet = new HashSet(50); //HashSet with initial capacity
2. 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
assetSet.add("I am first object in HashSet"); // add will return false as Set already has
3. 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");
}
System.out.println("HashSet is empty, does not contain any element");
}
4. 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
}
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
}
5. 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
6. 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
7. 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
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
8. How to convert HashSet into an array in Java
HashSet has a 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();
Set<String> stringSet = new HashSet<String>();
String[] strArray = stringSet.toArray();
After Java 1.5 this method accepts generics parameter and It can return the same type of element which is stored in HashSet. If the size of Array is not sufficient then a new Array with the runtime type of elements in HashSet is created. If you want to convert HashSet into Array List then search on Javarevisited.
And, if you are wondering how HashSet works in Java, here is a nice diagram which explains that its nothing but an HashMap with same values for each element:
That's all on this Java HashSet tutorial. HashSet in java is one of the frequently used Collection classes and can be very useful in certain scenarios where you need to store unique elements with quick retrieval. an important point to note about java HashSet it that add, remove, contains(), and size() is constant time operation.
Other Java tutorial on collection framework:
8 comments :
Which one is faster between HashSet and ArrayList ?
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..
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...
import java.util.*;
public class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
This would produce the following result:
[D, E, F, A, B, C]
Will you please explain me , in above program how this output come. ....??
see in Hashset the insertion order is not preserved!!! so output will come in random order!!
Why set is not adding different String objects with same value.? While in case of other objects its allowing adding of duplicates. Please look at the below sample code and explain :
public class Test {
public static void main( String[] args ) {
Set set = new HashSet ();
String a = new String("A");
String b = new String("A");
set.add( b );
set.add( a );
Set set1 = new HashSet ();
C c1 = new C( "Mohit" );
C c2 = new C( "Mohit" );
set1.add( c1 );
set1.add( c2 );
System.out.println(set.size()); // Result is 1
System.out.println(set1.size()); // Result is 2
}
}
class C{
private String name;
public C(String s){
name = s;
}
}
System.out.println(set.size()); // Result is 1
System.out.println(set1.size()); // Result is 2
As String is immutable and use string pool concept, so hashmap handles differently in case of String for generating hashcode.
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
I hope you are clear.
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
//check heading : How to convert HashSet into array : its error
public static void main(String[] args) {
Set set = new HashSet();
set.add("1");
set.add("2");
set.add("3");
set.add("4");
set.add("5");
String[] arr = set.toArray();
for (Object object : arr) {
System.out.println(object);
}
}
}
Post a Comment