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

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

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


当前回答

你可以在Java 6中做到:

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

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

其他回答

有点复杂,但可以在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));
}

你可以在Java 6中做到:

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

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

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

有几种方法:

双大括号初始化

这是一种创建匿名内部类的技术,它有一个实例初始化器,在创建实例时将string添加到自身:

Set<String> s = new HashSet<String>() {{
    add("a");
    add("b");
}}

请记住,这实际上会在每次使用HashSet时创建一个新的子类,尽管不必显式地编写一个新的子类。

一种实用方法

编写一个返回Set的方法并不是太难写:

public static Set<String> newHashSet(String... strings) {
    HashSet<String> set = new HashSet<String>();

    for (String s : strings) {
        set.add(s);
    }
    return set;
}

上面的代码只允许使用String类型,但是允许使用任何使用泛型的类型应该不会太难。

利用图书馆

许多库都有一个方便的方法来初始化集合对象。

例如,谷歌Collections有一个Sets.newHashSet(T…)方法,该方法将用特定类型的元素填充HashSet。