Java 如何通过构造初始化 HashSet 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2041778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:54:49  来源:igfitidea点击:

How to initialize HashSet values by construction?

javacollectionsconstructorinitializationhashset

提问by Serg

I need to create a Setwith 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.

有没有办法在一行代码中做到这一点?例如,它对最终静态字段很有用。

采纳答案by Gennadiy

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.

稍微不那么丑陋,效率对于静态初始化无关紧要。

回答by Bozho

Collection literals were scheduled for Java 7, but didn't make it in. So nothing automatic yet.

集合文字是为 Java 7 安排的,但没有加入。所以还没有自动。

You can use guava's Sets:

您可以使用番石榴的Sets

Sets.newHashSet("a", "b", "c")

Or you can use the following syntax, which will create an anonymous class, but it's hacky:

或者您可以使用以下语法,这将创建一个匿名类,但它很笨拙:

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

回答by coobird

There are a few ways:

有几种方法:

Double brace initialization

双括号初始化

This is a technique which creates an anonymous inner class which has an instance initializer which adds Strings to itself when an instance is created:

这是一种创建匿名内部类的技术,该内部类具有一个实例初始值设定项,该初始String值设定项在创建实例时将s添加到自身:

Set<String> s = new HashSet<String>() {{
    add("a");
    add("b");
}}

Keep in mind that this will actually create an new subclass of HashSeteach time it is used, even though one does not have to explicitly write a new subclass.

请记住,这实际上会在HashSet每次使用时创建一个新的子类,即使不必显式编写新的子类。

A utility method

实用方法

Writing a method that returns a Setwhich is initialized with the desired elements isn't too hard to write:

编写一个返回 a 的方法Set并用所需的元素初始化它并不难写:

public static Set<String> newHashSet(String... strings) {
    HashSet<String> set = new HashSet<String>();

    for (String s : strings) {
        set.add(s);
    }
    return set;
}

The above code only allows for a use of a String, but it shouldn't be too difficult to allow the use of any type using generics.

上面的代码只允许使用 a String,但允许使用任何类型的泛型应该不会太难。

Use a library

使用图书馆

Many libraries have a convenience method to initialize collections objects.

许多库都有一个方便的方法来初始化集合对象。

For example, Google Collectionshas a Sets.newHashSet(T...)method which will populate a HashSetwith elements of a specific type.

例如,Google Collections有一个Sets.newHashSet(T...)方法可以HashSet用特定类型的元素填充 a 。

回答by Jason Nichols

You can do it in Java 6:

你可以在 Java 6 中做到:

Set<String> h = new HashSet<String>(Arrays.asList("a", "b", "c"));

But why? I don't find it to be more readable than explicitly adding elements.

但为什么?我不认为它比显式添加元素更具可读性。

回答by Aaron Digulla

A bit convoluted but works from Java 5:

有点复杂,但可以从 Java 5 运行:

Set<String> h = new HashSet<String>(Arrays.asList(new String[] {  
    "a", "b"
}))

Use a helper method to make it readable:

使用辅助方法使其可读:

Set<String> h = asSet ("a", "b");

public Set<String> asSet(String... values) {
    return new HashSet<String>(java.util.Arrays.asList(values));
}

回答by Mark Elliot

A generalization of coobird's answer'sutility function for creating new HashSets:

coobird 的答案用于创建新HashSets效用函数的概括:

public static <T> Set<T> newHashSet(T... objs) {
    Set<T> set = new HashSet<T>();
    for (T o : objs) {
        set.add(o);
    }
    return set;
}

回答by Christian Ullenboom

In Java 8 I would use:

在 Java 8 中,我会使用:

Set<String> set = Stream.of("a", "b").collect(Collectors.toSet());

This gives you a mutable Setpre-initialized with "a" and "b". Note that while in JDK 8 this does return a HashSet, the specification doesn't guarantee it, and this might change in the future. If you specifically want a HashSet, do this instead:

这为您提供了一个Set用“a”和“b”预初始化的可变变量。请注意,虽然在 JDK 8 中这确实会返回 a HashSet,但规范并不能保证它,这可能会在未来发生变化。如果您特别想要 a HashSet,请改为执行以下操作:

Set<String> set = Stream.of("a", "b")
                        .collect(Collectors.toCollection(HashSet::new));

回答by LanceP

I feel the most readable is to simply use google Guava:

我觉得最易读的就是简单地使用google Guava:

Set<String> StringSet = Sets.newSet("a", "b", "c");

回答by ToxiCore

This is an elegant solution:

这是一个优雅的解决方案:

public static final <T> Set<T> makeSet(@SuppressWarnings("unchecked") T... o) {
        return new HashSet<T>() {
            private static final long serialVersionUID = -3634958843858172518L;
            {
                for (T x : o)
                   add(x);
            }
        };
}

回答by Lu55

If you have only one value and want to get an immutableset this would be enough:

如果您只有一个值并且想要获得一个不可变的集合,这就足够了:

Set<String> immutableSet = Collections.singleton("a");