• Java Data Structures Tutorial

Adding elements to a Set



You can add elements to the set using the add() method of the Set interface. This method accepts an element as parameter and appends the given element/object to the set.

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