如何通过构造初始化 HashSet 值? [英] How to initialize HashSet values by construction?

查看:32
本文介绍了如何通过构造初始化 HashSet 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用初始值创建一个Set.

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 line of code? For instance, it's useful for a final static field.

推荐答案

我使用了一个速记,它的时间效率不是很高,但可以放在一行中:

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.

这篇关于如何通过构造初始化 HashSet 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆