Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

java - 如何通过构造初始化HashSet值?(How to initialize HashSet values by construction?)

I need to create a Set with initial values.

(我需要创建一个具有初始值的Set 。)

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

Is there a way to do this in one line of code?

(有没有办法在一行代码中做到这一点?)

For instance, it's useful for a final static field.

(例如,它对于最终的静态字段很有用。)

  ask by Serg translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a shorthand that I use that is not very time efficient, but fits on a single line:

(我使用的一个速记不是很省时,但是适合单行:)

Set<String> h = new HashSet<>(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<>(Arrays.asList(SET_VALUES));

Slightly less ugly and efficiency does not matter for the static initialization.

(稍微不那么难看,效率对于静态初始化并不重要。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...