EN
Java - initialize HashSet at construction
0 points
In this article, we would like to show you how to initialize HashSet at the construction in Java.
Quick solution:
xxxxxxxxxx
1
Set<String> letters = new HashSet<>(Arrays.asList("A", "B", "C"));
In this example, to initialize letters
HashSet at the construction time, we use Arrays.asList()
method in the following way:
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Set<String> letters = new HashSet<>(Arrays.asList("A", "B", "C"));
7
8
System.out.println(letters);
9
}
10
}
Output:
xxxxxxxxxx
1
[A, B, C]
Note:
This approache is inefficient since it needs to create an array, convert it to a list, and use it to create a HashSet.
In this example, we use double curly braces to initialize letters
HashSet on its creation.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
Set<String> letters = new HashSet<>() {{
7
add("A");
8
add("B");
9
add("C");
10
}};
11
12
System.out.println(letters);
13
}
14
}
Output:
xxxxxxxxxx
1
[A, B, C]
Note:
This approache is inefficient since it needs to create anonymous class each time it's called