我需要创建一个具有初始值的集合。

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");

是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。


当前回答

随着java9和方便的工厂方法的发布,这可以以一种更干净的方式实现:

Set set = Set.of("a", "b", "c");

其他回答

你可以在Java 6中做到:

Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));

但是为什么呢?我不认为它比显式地添加元素更具有可读性。

如果你只有一个值,想要得到一个不可变的集合,这就足够了:

Set<String> immutableSet = Collections.singleton("a");
import com.google.common.collect.Sets;
Sets.newHashSet("a", "b");

or

import com.google.common.collect.ImmutableSet;
ImmutableSet.of("a", "b");

随着java9和方便的工厂方法的发布,这可以以一种更干净的方式实现:

Set set = Set.of("a", "b", "c");

可以使用静态块进行初始化:

private static Set<Integer> codes1=
        new HashSet<Integer>(Arrays.asList(1, 2, 3, 4));

private static Set<Integer> codes2 =
        new HashSet<Integer>(Arrays.asList(5, 6, 7, 8));

private static Set<Integer> h = new HashSet<Integer>();

static{
    h.add(codes1);
    h.add(codes2);
}