Creating a HashSet and Adding New Elements to It

Java HashSet Examples


This example shows how to create a HashSet using the HashSet() constructor, and add new elements to it using the add() method.

Creating a HashSet and Adding New Elements to It

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

public class CreateHashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        Set<String> daysOfWeek = new HashSet<>();

        // Adding new elements to the HashSet
        daysOfWeek.add("Monday");
        daysOfWeek.add("Tuesday");
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        daysOfWeek.add("Sunday");

        // Adding duplicate elements will be ignored
        daysOfWeek.add("Monday");

        System.out.println(daysOfWeek);
    }
}
# Output
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]

Comments