We have seen the Overview of Set in Java, Here we will see what is HashSet in java and how it is used.

HashSet in java is the child class of the Set Interface. Which uses a hashtable for the storage. 

Insertion order is not preserved in HashSet because elements in HashSet are stored using hashing mechanism. HashSet contains unique elements and allows null elements. HashSet is non-synchronized.

Constructors for HashSet in Java:

  • public HashSet(): Creates a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
  • public HashSet(Collection<? extends E> c): Creates a new set containing the elements in the specified collection.
  • public HashSet(int initialCapacity): Creates a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
  • public HashSet(int initialCapacity, float loadFactor): Creates a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

Example for HashSet Constructors.

Java Code
import java.util.HashSet;
public class Test {
public static void main(String[] args) throws Exception {
// 1. Using public HashSet():
HashSet<String> map1 = new HashSet<>();
map1.add(“ABCD”);
map1.add(“GSFE”);
System.out.println(“Map1 : ” + map1);
// 2. public HashSet(Collection<? extends E> c)
HashSet<String> map2 = new HashSet<>(map1);
map2.add(“KDGF”);
map2.add(“HJDK”);
System.out.println(“Map2 : ” + map2);

// 3. public HashSet(int initialCapacity)
HashSet<String> map3 = new HashSet<>(20);
map3.add(“KSHE”);
map3.add(“SBDH”);
System.out.println(“Map3 : ” + map3);

// 4. public HashSet(int initialCapacity, float loadFactor)
HashSet<String> map4 = new HashSet<>(20, 0.50F);
map4.add(“KAIL”);
map4.add(“CHAN”);
System.out.println(“Map4 : ” + map4);

}
}
Output:
Map1 : [GSFE, ABCD]
Map2 : [HJDK, GSFE, KDGF, ABCD]
Map3 : [KSHE, SBDH]
Map4 : [CHAN, KAIL]

Methods in Set Interface:

  • boolean add(E e): Adds the specified element to the set if it is not already present.
  • boolean addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to the set if they’re not already present.
  • void clear(): Removes all of the elements from the set.
  • boolean contains(Object o): Returns true if the set contains the specified element.
  • boolean containsAll(Collection<?> c): Returns true if the set contains all of the elements of the specified collection.
  • boolean equals(Object o): Compares the specified object with the set for equality.
  • int hashCode(): Returns the hash code value for the set.
  • boolean isEmpty(): Returns true if the set contains no elements.
  • Iterator<E> iterator(): Returns an iterator over the elements in the set.
  • boolean remove(Object o): Removes the specified element from the set if it is present (optional operation).
  • boolean removeAll(Collection<?> c): Removes from the set all of its elements that are contained in the specified collection (optional operation).
  • boolean retainAll(Collection<?> c): Retains only the elements in the set that are contained in the specified collection (optional operation).
  • int size(): Returns the number of elements in the set (its cardinality).
  • Object[] toArray(): Returns an array containing all of the elements in the set.
  • <T> T[] toArray(T[] a): Returns an array containing all of the elements in the set; the runtime type of the returned array is that of the specified array.

Methods in HashSet:

  • boolean add(E e): Adds the specified element to this set if it is not already present.
  • void clear(): Removes all of the elements from this set.
  • Object clone(): Returns an empty HashSet instance the elements are not cloned.
  • boolean contains(Object o): Returns true if this set contains the specified element.
  • boolean isEmpty(): Returns true if this set contains no elements.
  • Iterator<E> iterator(): Returns an iterator over the elements in this set.
  • boolean remove(Object o): Removes the specified element from this set if it is present.
  • int size(): Returns the number of elements present in the set.

Following is the example for all the above Set and HashSet methods:

Java Code
import java.util.HashSet;
import java.util.Iterator;

public class Test {
public static void main(String[] args) throws Exception {

HashSet<String> map1 = new HashSet<>();
map1.add(“ABCD”);
map1.add(“GSFE”);
map1.add(“HJDK”);
map1.add(“KSHE”);
map1.add(“SBDH”);
System.out.println(“Map1 : ” + map1);

HashSet<String> map2 = (HashSet<String>) map1.clone();
map2.addAll(map1);
System.out.println(“Map2 : ” + map2);
map2.clear();
System.out.println(“Map2 after clear: ” + map2);
System.out.println(“Map2 is empty: ” + map2.isEmpty());
map2.add(“GSFE”);
map2.add(“HJAL”);
System.out.println(“Map2 :” + map2);

System.out.println(“Map1 contains GSFE: ” + map1.contains(“GSFE”));
System.out.println(“Map1 contains All from map2: ” + map1.containsAll(map2));

map1.remove(“SBDH”);
System.out.println(“Map1 after remove SBDH: ” + map1);

map1.removeAll(map2);
System.out.println(“Map1 after removeAll map2 elements: ” + map1);

// adding elements in map2
map2.add(“ABCD”);
map2.add(“KSHE”);
System.out.println(“Map2 Updated: ” + map2);

map1.retainAll(map2);
System.out.println(“Map1 after retainAll map2 elements: ” + map1);
System.out.println(“Map1 size: ” + map1.size() + “, Map2 Size: ” + map2.size());

Object[] arr1 = map1.toArray();
String[] arr2 = new String[2];
arr2 = map2.toArray(arr2);
System.out.print(“arr1 elements: “);
for (Object a : arr1) {
System.out.print(” ” + a);
}
System.out.print(“\narr2 elements: “);
for (String a : arr2) {
System.out.print(” ” + a);
}

System.out.print(“\nMap2 elements usign iterator:”);
for (Iterator<String> iterator = map2.iterator(); iterator.hasNext();) {
String string = iterator.next();
System.out.print(” ” + string);
}
}
}
Output:
Map1 : [SBDH, KSHE, HJDK, GSFE, ABCD]
Map2 : [HJDK, GSFE, ABCD, SBDH, KSHE]
Map2 after clear: []
Map2 is empty: true
Map2 :[GSFE, HJAL]
Map1 contains GSFE: true
Map1 contains All from map2: false
Map1 after remove SBDH: [KSHE, HJDK, GSFE, ABCD]
Map1 after removeAll map2 elements: [KSHE, HJDK, ABCD]
Map2 Updated: [GSFE, HJAL, ABCD, KSHE]
Map1 after retainAll map2 elements: [KSHE, ABCD]
Map1 size: 2, Map2 Size: 4
arr1 elements: KSHE ABCD
arr2 elements: GSFE HJAL ABCD KSHE
Map2 elements usign iterator: GSFE HJAL ABCD KSHE

-A blog by Shwetali Khambe

Related Posts