问题
In Java, how do I create a final Set that's populated at construction? I want to do something like the following:
static final Set<Integer> NECESSARY_PERMISSIONS
= new HashSet<Integer>([1,2,3,6]);
but I don't know the proper syntax in Java.
回答1:
Try this idiom:
import java.util.Arrays;
new HashSet<Integer>(Arrays.asList(1, 2, 3, 6))
回答2:
You might consider using Guava's ImmutableSet:
static final Set<Integer> NECESSARY_PERMISSIONS = ImmutableSet.<Integer>builder()
.add(1)
.add(2)
.add(3)
.add(6)
.build();
static final Set<String> FOO = ImmutableSet.of("foo", "bar", "baz");
Among other things, this is significantly faster (and ~3 times more space-efficient) than HashSet
.
回答3:
The easiest way, using standard Java classes, is
static final Set<Integer> NECESSARY_PERMISSIONS =
Collections.unmodifiableSet(new HashSet<Integer>(Arrays.asList(1, 2, 3, 6)));
But you can also use a static initializer, or delegate to a private static method:
static final Set<Integer> NECESSARY_PERMISSIONS = createNecessaryPermissions();
Note the unmodifiableSet
wrapper, which guarantees that your constant set is indeed constant.
回答4:
Using Google Guava library you can use ImmutableSet, which is designed exactly to this case (constant values):
static final ImmutableSet<Integer> NECESSARY_PERMISSIONS =
ImmutableSet.of(1,2,3,6);
Old-school way (without any library):
static final Set<Integer> NECESSARY_PERMISSIONS =
new HashSet<Integer>(Arrays.asList(1,2,3,6));
EDIT:
In Java 9+ you can use Immutable Set Static Factory Methods:
static final Set<Integer> NECESSARY_PERMISSIONS =
Set.of(1,2,3,6);
回答5:
You can do this in the following way which IMO is much better and more concise than other examples in this topic:
public static <T> Set<T> set(T... ts) {
return new HashSet<>(Arrays.asList(ts));
}
after importing it statically you can write something like this:
public static final Set<Integer> INTS = set(1, 2, 3);
回答6:
Set<String> s = new HashSet<String>() {{
add("1"); add("2"); add("5");
}};
来源:https://stackoverflow.com/questions/9470316/creating-prepopulated-set-in-java