EN
Java - add items to HashSet
0
points
In this article, we would like to show you how to add items to the HashSet in Java.
Quick solution:
Set<String> animals = new HashSet<>();
animals.add("Dog");
Practical example
In this example, we add three elements to the animals
HashSet using add()
method.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> animals = new HashSet<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Parrot");
System.out.println(animals); // [Parrot, Cat, Dog]
}
}
Output:
[Parrot, Cat, Dog]
Note:
HashSet doesn't accept duplicates. It only stores unique values.