- This class implements the Set interface.
- HashSet uses hashtable to store the elements.
- HashSet doesn’t maintain any order, the elements would be returned in any random order.
- HashSet contains unique elements only.
- HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
- HashSet allows null values however if you insert more than one nulls it would still return only one null value.
- HashSet is non-synchronized.
class HashSet<T>
We can create HashSet for storing String type elements as follows:
HashSet<String> hs=new HashSet<String> ();
We can create HashSet for storing Integer type elements as follows:
HashSet<Integer> hs=new HashSet<Integer> ();
HashSet contains the following constructors:
- HashSet (): It is constructors default hash set.
- HashSet (Collection c): It initializes hash set by using elements of c.
- HashSet (int capacity): It creates HashSet with initial capacity , default capacity of HashSet is 16.
- HashSet (int capacity, float fillRatio): it initializes capacity and fillRatio to grow the capacity after certain elements inserted.
HashSet Example
- import java.util.*;
- class MyHashSetDeo{
- public static void main(String args[]){
- HashSet<String> hs=new HashSet<String>();
- hs.add(“A”);
- hs.add(“B”);
- hs.add(“C”);
- hs.add(“D”);
- Iterator<String> itr=hs.iterator();
- while(itr.hasNext()){
- System.out.println(itr.next());
- }
- }
- }
Output:
A
B
C
D
HashSet Methods:
- boolean add(Element e): It adds the element e to the list.
- void clear(): It removes all the elements from the list.
- Object clone(): This method returns a shallow copy of the HashSet.
- boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
- boolean isEmpty(): Returns true if there is no element present in the Set.
- int size(): It gives the number of elements of a Set.
- boolean(Object o): It removes the specified Object o from the Set.
HashSet Example
import java.util.HashSet;
public class MyHashSetDemo1 {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hset =new HashSet<String>();
// Adding elements to the HashSet
hset.add("A");
hset.add("M");
hset.add("G");
hset.add("O");
hset.add("B");
//Addition of duplicate elements
hset.add("A");
hset.add("M");
//Addition of null values
hset.add(null);
hset.add(null);
//Displaying HashSet elements
System.out.println(hset);
}
}
Output:
[null, M, G, A, O, B]