如何通过构造初始化HashSet值? [英] How to initialize HashSet values by construction?
本文介绍了如何通过构造初始化HashSet值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用初始值创建设置
。
设置< String> h = new HashSet< String>();
h.add(a);
h.add(b);有一种方法可以在一个命令中做到这一点?
解决方案有一个我用的速记不是很有效率,但适合单行:
设置< String> h = new HashSet< String>(Arrays.asList(a,b));
同样,这不是时间效率,因为你正在构造一个数组,转换为列表,
初始化静态最终集时,我通常这样写:
public static final String [] SET_VALUES = new String [] {a,b};
public static final Set< String> MY_SET = new HashSet< String>(Arrays.asList(SET_VALUES));
稍微不那么丑陋和效率对静态初始化无关紧要。
I need to create a Set
with initial values.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Is there a way to do this in one command?
解决方案 There is a shorthand that I use that is not very time efficient, but fits on a single line:
Set<String> h = new HashSet<String>(Arrays.asList("a", "b"));
Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.
When initializing static final sets I usually write it like this:
public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<String>(Arrays.asList(SET_VALUES));
Slightly less ugly and efficiency does not matter for the static initialization.
这篇关于如何通过构造初始化HashSet值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文