我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
当前回答
有点复杂,但可以在Java 5中工作:
Set<String> h = new HashSet<String>(Arrays.asList(new String[] {
"a", "b"
}))
使用helper方法使其可读:
Set<String> h = asSet ("a", "b");
public Set<String> asSet(String... values) {
return new HashSet<String>(java.util.Arrays.asList(values));
}
其他回答
如果Set的包含类型是枚举类型,则存在java构建的工厂方法(从1.5开始):
Set<MY_ENUM> MY_SET = EnumSet.of( MY_ENUM.value1, MY_ENUM.value2, ... );
你可以在Java 6中做到:
Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));
但是为什么呢?我不认为它比显式地添加元素更具有可读性。
使用Java 8,我们可以创建HashSet为:
Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
如果我们想要不可修改的集合,我们可以创建一个实用方法:
public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
return Collector.of(
supplier,
Set::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableSet);
}
此方法可用于:
Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));
只是一个小提示,不管你最终使用了这里提到的哪种好方法,如果这是一个通常不被修改的默认设置(就像你正在创建的库中的默认设置),遵循以下模式是一个好主意:
// Initialize default values with the method you prefer, even in a static block
// It's a good idea to make sure these defaults aren't modifiable
private final static Set<String> DEFAULT_VALUES = Collections.unmodifiableSet(...);
private Set<String> values = DEFAULT_VALUES;
好处取决于您为该类创建的实例数量以及更改默认值的可能性。
如果您决定遵循这种模式,那么您还必须选择最易读的集初始化方法。由于不同方法之间的效率差异可能不会太大,因为您将只初始化一次集合。
最方便的方法之一是使用泛型Collections.addAll()方法,该方法接受一个集合和可变参数:
Set<String> h = new HashSet<String>();
Collections.addAll(h, "a", "b");