• Java Data Structures Tutorial

Java Data Structures - Creating a Set



The interface Set of the java.util package represents the set in Java. The classes HashSet and LinkedHashSet implements this interface.

To create a set (object) you need to instantiate either of these classes.

Set set = new HashSet();

Example

import java.util.HashSet;
import java.util.Set;

public class CreatingSet {
   public static void main(String args[]) {      
      Set set = new HashSet();      
      set.add(100);
      set.add(501);
      set.add(302);
      set.add(420);
      System.out.println("Contents of the set are: "+set);	   
   }
}

Output

Contents of the set are: [100, 420, 501, 302]
Advertisements