java 在构造函数或字段声明中初始化 List

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

Initializing List in constructor or field declaration

javaarraysinitialization

提问by Jankosha

I was wondering whether there is a difference in initializing objects like ArrayList<> and stuff in field declaration or constructor.

我想知道在初始化像 ArrayList<> 这样的对象和字段声明或构造函数中的东西是否有区别。

Is there a difference in memory usage, performance or anything like that or is it completely the same?

内存使用、性能或类似的东西有区别还是完全相同?

Option 1:

选项1:

class MyClass {
     private List<String> strings = new ArrayList<String>();
}

Option 2:

选项 2:

class MyClass {
    private List<String> strings;
    public MyClass() {
        strings = new ArrayList<String>();
    }
}

It may be a stupid question, or a very basic one, but I like to build from the start, I like to understand all that I see.

这可能是一个愚蠢的问题,或者一个非常基本的问题,但我喜欢从头开始构建,我喜欢理解我所看到的一切。

回答by Bohemian

There is a difference: wheninitialization occurs. Fields are initialized first, then the constructor fires.

是有区别的:初始化发生。字段首先被初始化,然后构造函数被触发。

In your trivial example, there would be no practical difference, but if another field depended on the List field for initialization, the constructor version would explode with a NPE.

在您的简单示例中,没有实际区别,但是如果另一个字段依赖于 List 字段进行初始化,则构造函数版本将与 NPE 一起爆炸。

Consider:

考虑:

 private List<String> strings = Arrays.asList("foo", "bar");
 private String stringsDescription = strings.toString();

If you moved initialization of stringsto the constructor, the initialization of stringsDescriptionwould explode with a NPE.

如果您将初始化移动strings到构造函数,则初始化stringsDescription将与 NPE 一起爆炸。

回答by Tim B

It's essentially the same thing. Doing it in the constructor gives more control over it (for example different constructors can do different things) but the final result is identical.

本质上是一样的。在构造函数中执行它可以更好地控制它(例如,不同的构造函数可以做不同的事情)但最终结果是相同的。

You will see no performance difference in memory, CPU, or anything else doing it either way.

无论哪种方式,您都不会看到内存、CPU 或其他任何方面的性能差异。

回答by Gervasio Amy

take a look at this Default constructor vs. inline field initialization

看看这个默认构造函数与内联字段初始化

There's also other ways to initialize values: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

还有其他初始化值的方法:https: //docs.oracle.com/javase/tutorial/java/javaOO/initial.html

IMHO, initializing in default constructor is a little bit more risky unless you are sure that is the only constructor you have. If you have more than one, you need to call always default (good practice) or duplicate your initialization code.

恕我直言,在默认构造函数中初始化有点冒险,除非您确定这是唯一的构造函数。如果您有多个,则需要始终调用默认值(良好做法)或复制您的初始化代码。