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:
xxxxxxxxxx
1
Set<String> animals = new HashSet<>();
2
animals.add("Dog");
In this example, we add three elements to the animals
HashSet using add()
method.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Set<String> animals = new HashSet<>();
7
8
animals.add("Dog");
9
animals.add("Cat");
10
animals.add("Parrot");
11
12
System.out.println(animals); // [Parrot, Cat, Dog]
13
}
14
}
Output:
xxxxxxxxxx
1
[Parrot, Cat, Dog]
Note:
HashSet doesn't accept duplicates. It only stores unique values.