我需要Set使用初始值创建一个。Set<String> h = new HashSet<String>();h.add("a");h.add("b");有没有办法在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
3 回答

慕慕森
TA贡献1856条经验 获得超17个赞
我使用的一个速记不是很省时,但是可以放在一行上:
Set<String> h = new HashSet<>(Arrays.asList("a", "b"));
同样,这不是省时的,因为您正在构造数组,转换为列表并使用该列表创建集合。
当初始化静态最终集时,我通常这样写:
public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));
稍微不那么丑陋,效率对于静态初始化并不重要。

Helenr
TA贡献1780条经验 获得超4个赞
集合文字是为Java 7排定的,但没有加入。因此,还没有自动的方法。
您可以使用番石榴的Sets:
Sets.newHashSet("a", "b", "c")
或者,您可以使用以下语法,这将创建一个匿名类,但它很hacky:
Set<String> h = new HashSet<String>() {{
add("a");
add("b");
}};
添加回答
举报
0/150
提交
取消