Creating prepopulated set in Java [duplicate]

2019-02-21 11:44发布

问题:

This question already has an answer here:

  • How to initialize HashSet values by construction? 22 answers

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));


回答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");  
}};