How to create a HashSet in Java?

Java 8Object Oriented ProgrammingProgramming

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.

The following is an example to create a HashSet.

Declare a HashSet object

HashSet hs = new HashSet();

Now, add some elements

hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");

Now display the HashSet elements as shown below

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println(hs);
   } 
}

Output

[A, B, C, D, E, F, K, M, N]
raja
Updated on 30-Jul-2019 22:30:24

Advertisements