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]
Related Java HashSet Source Code Examples
- Creating a HashSet and Adding New Elements to It
- Java 8 forEach() Set Example
- Java Convert Array to Set
- Iterating over a HashSet using Iterator
- Iterate over HashSet in Java
- Remove Element from HashSet in Java
- Create HashSet in Java
Collection Framework
HashSet
Java
Comments
Post a Comment