如何在 Java 中初始化 Set?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26249709/
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-11 02:05:39  来源:igfitidea点击:

How do I initialize a Set in Java?

javacollectionsinitializationset

提问by Micromancer

This is fine...

这可以...

public class someClass {
   private Set<Element> pre;

   public void someMethod() {
      pre.add(new Element());
   }
}

But this isn't...

但这不是...

public class someClass {

    public void someMethod() {
       Set<Element> pre;
       pre.add(new Element());
    }
}

What's the correct syntax for the latter case without just turning it into the former?

后一种情况的正确语法是什么而不只是将其转换为前者?

回答by Eran

In both cases you are missing the initialization of the Set, but in the first case it's initialized to nullby default, so the code will compile, but will throw a NullPointerExceptionwhen you try to add something to the Set. In the second case, the code won't even compile, since local variables must be assigned a value before being accessed.

在这两种情况下,你缺少的初始化Set,但在第一种情况下它初始化为null默认,所以代码可以编译,但会抛出NullPointerException当您尝试添加一些的Set。在第二种情况下,代码甚至无法编译,因为在访问局部变量之前必须为其赋值。

You should fix both examples to

您应该将这两个示例修复为

private Set<Element> pre = new HashSet<Element>();

and

Set<Element> pre = new HashSet<Element>();

Of course, in the second example, the Setis local to someMethod(), so there's no point in this code (you are creating a local Setwhich you are never using).

当然,在第二个示例中,Set是本地的someMethod(),因此此代码没有意义(您正在创建一个Set从未使用过的本地)。

HashSetis one implementation of Setyou can use. There are others. And if your know in advance the number of distinct elements that would be added to the Set, you can specify that number when constructing the Set. It would improve the Set's performance, since it wouldn't need to be re-sized.

HashSetSet您可以使用的一种实现。还有其他人。如果您事先知道将添加到 的不同元素的数量Set,则可以在构造Set. 这将提高Set的性能,因为它不需要重新调整大小。

private Set<Element> pre = new HashSet<Element>(someInitialSize);