我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
我需要创建一个具有初始值的集合。
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
是否有一种方法可以在一行代码中做到这一点?例如,它对于最终的静态字段很有用。
当前回答
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("a", "b", "c");
这是可变的。
其他回答
集合字面值计划在Java 7中使用,但最终没有加入。所以还没有自动的东西。
你可以使用番石榴的套装:
Sets.newHashSet("a", "b", "c")
或者你可以使用下面的语法,这将创建一个匿名类,但它是hack:
Set<String> h = new HashSet<String>() {{
add("a");
add("b");
}};
如果Set的包含类型是枚举类型,则存在java构建的工厂方法(从1.5开始):
Set<MY_ENUM> MY_SET = EnumSet.of( MY_ENUM.value1, MY_ENUM.value2, ... );
我觉得最有可读性的是简单地使用谷歌番石榴:
Set<String> StringSet = Sets.newHashSet("a", "b", "c");
这是可变的。
有一个我使用的简写,不是很省时,但适合单行:
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));
对于静态初始化来说,稍微不那么丑陋和效率并不重要。
可以使用静态块进行初始化:
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);
}