Date: 2012sep23
Update: 2025sep27
Language: Java
Keywords: init
Q. Java: How to initialize a HashSet
A. Here is a nice way to do it.
Shown as a full example:
import java.util.HashSet;
class Demo {
static HashSet<String> shoppingList = new HashSet<>() {{
add("milk");
add("peanut butter");
add("bread");
}};
// Notice the double brackets
public static final void main(String []args) {
for (var entry : shoppingList) {
System.out.println("entry=" + entry);
}
}
}
Output:
entry=bread
entry=peanut butter
entry=milk
Some people don't like the double brace brackets because it
creates an anonymous inner class. But I like it because its compact.