HashSet in Java Collection Example

  • HashSet is a class of collection framework which extends AbstractSet class and implements the Set interface.
  • HasSet doesn't guarantee that elements order will remain same over the time and returned in any random order.
  • HasSet doesn't allow duplicate values. If you try to insert duplicate, It will overwrite.
  • HasSet allows to store null values.
  • HasSet implementation is not synchronized.
Hashset hierarchy in Java Collection

Important Methods of HashSet
  • boolean add(E e) : To add elements in to set if it is not already present.
  • void clear() : Remove all entries from set.
  • Object clone() : It will returns shallow copy of HasSet instance.
  • boolean contains(Object o) : It will return true if given values is present in HashSet.
  • boolean isEmpty() : It will return true if HasSet is empty.
  • Iterator<E> iterator() : It will returns an iterator over the elements in Set.
  • boolean remove(Object o) : It will remove specified elements from set if it is available in HashSet.
  • int size() : It will return size of HashSet.
Bellow given example will show you usage of different HashSet methods.
Example Of HashSet in Java
package JAVAExamples;

import java.util.HashSet;

public class HashSetJavaExample {
 public static void main(String args[]) {
 HashSet hset = new HashSet();
 //Check if HashSet is empty.
 System.out.println("HashSet is empty? : "+hset.isEmpty());
 //Add elements in HashSet.
 hset.add("One");
 hset.add("Two");
 hset.add("Three");
 hset.add(null); //HassSet allows null values.
 hset.add("Four");
 //Print HashSet.
 System.out.println("HashSet elements are : "+hset);
 //Check HashSet size.
 System.out.println("Size of HashSet is : "+hset.size());
 //Removing element from HashSet.
 hset.remove("Two");
 System.out.println("Now HashSet elements are : "+hset);
 }
}

Output :
HashSet is empty? : true
HashSet elements are : [null, One, Four, Two, Three]
Size of HashSet is : 5
Now HashSet elements are : [null, One, Four, Three]

This way, You can use HashSet to store values in random order including null.

No comments:

Post a Comment