HashSet Class

HashSet Class

In this tutorial, we are going to discuss HashSet class in java. This class implements the Set interface, backed by a hash table (actually a HashMap instance).

  • The underlying data structure is the Hash table.
  • Insertion order is not preserved, and it is based on the hash code of the objects.
  • Duplicate objects are not allowed.
  • If we are trying to insert duplicate objects, we won’t get a compile-time error, and the runtime error add() method simply returns false.
  • Heterogeneous objects are allowed.
  • Null insertion is possible. (only once)
  • HashSet is non-synchronized.
  • Implements Serializable and Cloneable interfaces but not RandomAccess.
  • HashSet is best suitable if our frequent operation is “Search.”
HashSet Class
Constructors

1. HashSet h = new HashSet()

Creates an empty HashSet object with default initial value 16 and default fill ratio 0.75

2. HashSet h = new HashSet(int initialcapacity)

3. HashSet h = new HashSet(int initialCapacity, float fillratio)

Here fillratio is 0 or 1.

4. HashSet h = new HashSet(Collection c)

Note

After filling how much ratio new HashSet object will be created , The ratio is called “FillRatio” or “LoadFactor“.

package com.ashok.collections.hashset;

import java.util.HashSet;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyHashSet {
   public static void main(String args[]) {
      // HashSet declaration
      HashSet<string> hset = new HashSet<string>();
      // Adding elements to the HashSet
      hset.add("Ashok");
      hset.add("Vinod");
      hset.add("Dillesh");
      hset.add("Thiru");
      hset.add("Naresh");
      System.out.println(hset);
  
      // Addition of duplicate elements
      System.out.println(hset.add("Ashok"));

      System.out.println(hset);
  
      // Addition of null values
      hset.add(null);
      System.out.println(hset.add(null));
  
      // Displaying HashSet elements
      System.out.println(hset);
   }
}

Output

[Thiru, Ashok, Dillesh, Vinod, Naresh]
false
[Thiru, Ashok, Dillesh, Vinod, Naresh]
false
[null, Thiru, Ashok, Dillesh, Vinod, Naresh]

That’s all about the HashSet Class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

HashSet Class
Scroll to top