在构造函数或字段声明中初始化List [英] Initializing List in constructor or field declaration
问题描述
我想知道在初始化对象(如ArrayList<>)和字段声明或构造函数中的内容是否存在差异。
I was wondering whether there is a difference in initializing objects like ArrayList<> and stuff in field declaration or constructor.
内存使用情况,性能或其他类似情况是否存在差异或完全相同?
Is there a difference in memory usage, performance or anything like that or is it completely the same?
选项1:
class MyClass {
private List<String> strings = new ArrayList<String>();
}
选项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.
推荐答案
存在差异:初始化时。字段首先被初始化,然后构造函数被激活。
There is a difference: when initialization occurs. Fields are initialized first, then the constructor fires.
在你的简单例子中,没有实际的区别,但如果另一个字段依赖于List字段进行初始化,构造函数版本会随NPE爆炸。
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.
考虑:
private List<String> strings = Arrays.asList("foo", "bar");
private String stringsDescription = strings.toString();
如果您将字符串
的初始化移至构造函数, stringsDescription
的初始化会随NPE爆炸。
If you moved initialization of strings
to the constructor, the initialization of stringsDescription
would explode with a NPE.
这篇关于在构造函数或字段声明中初始化List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!