Download java util HashSet Class in Formats
QR Code for this Page
java util HashSet Class

java util HashSet Class

java.util.HashSet Class

HashSet Class in Java

The Java Collection Framework introduces the HashSet collection. This implementation is backed by a hash table (HashMap, actually) for storing unique elements. The backing hash table ensures that duplicate elements are avoided as each element is stored and retrieved through its hash code, providing constant retrieval time.

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. Most of the HashSet functionality is provided through the AbstractCollection and AbstractSet superclasses, which HashSet shares with TreeSet.

Is HashSet Thread Safe ?

The HashSet is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set.

To prevent accidental unsynchronized access to the set, you should create set with Collections.synchronizedSet method.

What is the Performance a HashSet in Java ?

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

In this tutorial you can learn about java.util.HashSet class and its examples. And also learn how to use java.util.HashSet class.

java.util.HashSet class Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*  Java HashSet class Example
    Save with file name HashSetExample.java */
  
import java.util.HashSet;
  
public class HashSetExample
{
  public static void main(String args[])
  {
    //java.util.HashSet DECLARATION
    HashSet hs;
    //java.util.HashSet OBJECT CREATION
    //USING DEFAULT CONSTRUCTOR
    hs = new HashSet();
    //ADD AN ELEMENT
    hs.add("Huda Tutorials");
    hs.add("Java Tutorials");
    //DUPLICATES NOT ALLOWED
    hs.add("Huda Tutorials");
    hs.add("C Tutorials");
    hs.add("CPP Tutorials");
    //RETURNS COUNT OF ELEMENTS HashSet CONTAINS
    System.out.println("Elements Count : " + hs.size());
    //java.util.HashSet OUTPUT
    System.out.println(hs);
  }
}

The following example shows how to use HashSet with Iterator.

How to use HashSet with Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*  How to use HashSet with Iterator Example
    Save with file name HashSetExample2.java  */
  
import java.util.HashSet;
import java.util.Iterator;
  
public class HashSetExample2
{
  public static void main(String args[])
  {
    //java.util.HashSet DECLARATION
    HashSet hs;
    //java.util.HashSet OBJECT CREATION
    //USING DEFAULT CONSTRUCTOR
    hs = new HashSet();
    //ADD AN ELEMENT
    hs.add("Huda Tutorials");
    hs.add("Java Tutorials");
    //DUPLICATES NOT ALLOWED
    hs.add("Huda Tutorials");
    hs.add("C Tutorials");
    hs.add("CPP Tutorials");
    //RETURNS COUNT OF ELEMENTS HashSet CONTAINS
    System.out.println("Elements Count : " + hs.size());
    //java.util.HashSet OUTPUT
    Iterator itr = hs.iterator();
    while(itr.hasNext())
    {
      System.out.println(itr.next());
    }
  }
}

The following example shows how to use HashSet with Arrays, Set and Iterator.

How to use HashSet with Arrays, Set and Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*  How to use HashSet with Arrays, Set and Iterator Example
    Save with file name HashSetExample3.java  */
  
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
  
public class HashSetExample3
{
  public static void main(String args[])
  {
    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
    Set s; //java.util.Set DECLARATION
    //java.util.Set OBJECT CREATION USING ARRAY AS LIST
    s = new HashSet(Arrays.asList(elements));
    //java.util.Set OUTPUT
    Iterator itr = s.iterator();
    while(itr.hasNext())
    {
      System.out.println(itr.next());
    }
  }
}

java.util.HashSet class Example 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*  Java HashSet class Example 4
    Save with file name HashSetExample4.java  */
  
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
  
public class HashSetExample4
{
  public static void main(String args[])
  {
    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
    Set s; //java.util.Set DECLARATION
    //java.util.Set OBJECT CREATION USING ARRAY AS LIST
    s = new HashSet(Arrays.asList(elements));
    //ADD ELEMENT TO Set COLLECTION
    s.add("NetBeans Tutorials");
    //DISPLAY SIZE OF THE Set COLLECTION
    System.out.println("Set Collection Size : "+s.size());
    //CHECK THE Set COLLECTION IS EMPTY
    System.out.println("Set Collection is Empty : "+s.isEmpty());
    //CHECK THE GIVEN ELEMENT IN Set COLLECTION
    System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials"));
    //java.util.Set OUTPUT
    System.out.println("Elements Before Element Remove");
    Iterator itr = s.iterator();
    while(itr.hasNext())
    {
      System.out.println(itr.next());
    }
    s.remove("C Tutorials");
    System.out.println("Elements After Element Remove");
    itr = s.iterator();
    while(itr.hasNext())
    {
      System.out.println(itr.next());
    }
  }
}

The following example shows how to compare two Set Collections.

How to compare two Set Collections

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*  How to compare two Set Collections Example
    Save with file name HashSetExample5.java  */
  
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
  
public class HashSetExample5
{
  public static void main(String args[])
  {
    String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
    String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};
    //java.util.Set DECLARATION
    Set s, s2;
    //java.util.Set OBJECT CREATION USING ARRAY AS LIST
    s = new HashSet(Arrays.asList(elements));
    s2 = new HashSet(Arrays.asList(elements2));
    //COMPARE TWO COLLECTIONS
    System.out.println("Equals : " + s2.equals(s));
    //CONTAINS COLLECTION IN OTHER COLLECTION
    System.out.println("Contains : " + s2.containsAll(s));
  }
}

The following example shows how to save Set Collection into file.

How to save Set Collection into file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*  How to save Set Collection into file Example
    Save with file name HashSetExample6.java  */
  
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
  
public class HashSetExample6
{
  public static void main(String args[])
  {
    try
    {
      String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};
      //java.util.Set DECLARATION
      Set s;
      //java.util.Set OBJECT CREATION USING ARRAY AS LIST
      s = new HashSet(Arrays.asList(elements));
      //FileOutputStream CREATION
      FileOutputStream fos = new FileOutputStream("set.set");
      //ObjectOutputStream CREATION
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      //WRITE Set OBJECT TO ObjectOutputStream
      oos.writeObject(s);
      //CLOSE THE ObjectOutputStream
      oos.close();
      System.out.println("Set Collection Saved into File Sucessfully");
    }
    catch(Exception e)
    {
      System.out.println("Error Occurred : " + e.getMessage());
    }
  }
}

The following example shows how to retrieve Set Collection from file.

How to retrieve Set Collection from file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*  How to retrieve Set Collection from file Example
    Save with file name HashSetExample7.java  */
  
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
  
public class HashSetExample7
{
  public static void main(String args[])
  {
    try
    {
      //java.util.Set DECLARATION
      Set s;
      //FileInputStream CREATION
      FileInputStream fis = new FileInputStream("set.set");
      //ObjectInputStream CREATION
      ObjectInputStream ois = new ObjectInputStream(fis);
      //READ Set OBJECT FROM ObjectInputStream
      s = (Set) ois.readObject();
      ois.close();
      System.out.println(s);
    }
    catch(Exception e)
    {
      System.out.println("Error Occurred : " + e.getMessage());
    }
  }
}
Download java util HashSet Class in Formats