Tutorials

Collection Programs


HashSet Add item


In this chapter, our task is:

  • We will create a HashSet
  • We will add elements to HashSet (duplicate as well)
  • We will print the set

Example: Add elements to HashSet in java


package javaRadarHashSet;

import java.util.HashSet;

public class SimpleHashSet {

      public static void main(String[] args) {

            //create HashSet
            HashSet javaRadarSet = new HashSet();

            //Add elements to HashSet
            javaRadarSet.add("Java");
            javaRadarSet.add("Java");
            javaRadarSet.add("Spring");
            javaRadarSet.add("Hibernate");
            javaRadarSet.add("EJB");
            
            //print the set
            System.out.println(javaRadarSet);

      }

}

OUTPUT

[Java, Hibernate, Spring, EJB]

 

Points to note

  • As we know Set doesn't allow duplicate elements, so "Java" is added just one time in the HashSet even though we added it twice. (See the code)

To read about HashSet in details, Click here



Please Share this page
Views : 28