我需要创建一个具有初始值的集合。
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 6中做到:
Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));
但是为什么呢?我不认为它比显式地添加元素更具有可读性。
其他回答
集合字面值计划在Java 7中使用,但最终没有加入。所以还没有自动的东西。
你可以使用番石榴的套装:
Sets.newHashSet("a", "b", "c")
或者你可以使用下面的语法,这将创建一个匿名类,但它是hack:
Set<String> h = new HashSet<String>() {{
add("a");
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));
}
在Eclipse Collections中,有几种不同的方法来初始化一个包含字符'a'和'b'的Set语句。Eclipse Collections同时为对象类型和基本类型提供了容器,因此我演示了如何使用Set<String>或CharSet,以及可变、不可变、同步和不可修改的这两个版本。
Set<String> set =
Sets.mutable.with("a", "b");
HashSet<String> hashSet =
Sets.mutable.with("a", "b").asLazy().into(new HashSet<String>());
Set<String> synchronizedSet =
Sets.mutable.with("a", "b").asSynchronized();
Set<String> unmodifiableSet =
Sets.mutable.with("a", "b").asUnmodifiable();
MutableSet<String> mutableSet =
Sets.mutable.with("a", "b");
MutableSet<String> synchronizedMutableSet =
Sets.mutable.with("a", "b").asSynchronized();
MutableSet<String> unmodifiableMutableSet =
Sets.mutable.with("a", "b").asUnmodifiable();
ImmutableSet<String> immutableSet =
Sets.immutable.with("a", "b");
ImmutableSet<String> immutableSet2 =
Sets.mutable.with("a", "b").toImmutable();
CharSet charSet =
CharSets.mutable.with('a', 'b');
CharSet synchronizedCharSet =
CharSets.mutable.with('a', 'b').asSynchronized();
CharSet unmodifiableCharSet =
CharSets.mutable.with('a', 'b').asUnmodifiable();
MutableCharSet mutableCharSet =
CharSets.mutable.with('a', 'b');
ImmutableCharSet immutableCharSet =
CharSets.immutable.with('a', 'b');
ImmutableCharSet immutableCharSet2 =
CharSets.mutable.with('a', 'b').toImmutable();
注意:我是Eclipse Collections的提交者。
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("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);
}