在Java中初始化ArrayList字段的最佳实践 [英] Best practice for initializing an ArrayList field in Java

查看:96
本文介绍了在Java中初始化ArrayList字段的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中初始化ArrayList字段的最佳做法是什么(以避免测试空值)?

What's the best practice for initializing an ArrayList field in Java (to avoid testing null value) ?

在声明时,如下所示:

private List<String> myList = new ArrayList<String>();

或者在吸气剂中,如下所示:

Or in the getter, like this :

public List<String> getMyList() {
    if(myList == null) {
        myList = new ArrayList<String>();
    }
    return myList;
}

或者,在构造函数中:

public Test(){
    myList = new ArrayList<String>();
}

也许是一样的,但是我很好奇.

Maybe it's the same, but I am curious to know.

推荐答案

第一个选项允许您执行

private final List<String> myList = new ArrayList<>();

因此可以防止您以后意外创建一个全新的列表;从而帮助解决(很多不是全部)多线程问题.除此之外,现在编译器还可以帮助您确保一次准确地初始化您的字段.

Thus preventing you from accidentally creating a completely new list later on; thus helping with (many, not all) multi-threading issues. In addition to that, now the compiler can help you to make sure that your field is initialized exactly once.

除此之外,第二个选项可以看作是惰性初始化".从这个意义上来说,它可以看作是优化选择"!从那里开始:许多人提倡避免过早的优化!

Beyond that, the second option can be seen as "lazy initialization". And in that sense: it can be seen as "optimization choice"! And from there: many people advocate on avoiding premature optimization!

您知道,当您不能依赖已创建的列表时,可能会造成很多麻烦.因此,即使从这种角度来看,您还有另一个理由更喜欢选项1!

You know, when you can't rely on the list being already created that can cause a lot of trouble. So even when coming from that perspective, you have another argument to prefer option 1!

编辑,关于编译器选项:从语义上讲,选项1和3(或多或少)是相等"的[提示:如果您发现选择option1或option3会对代码产生影响. .这将很好地表明您在代码中做错了非常严重的事情).

Edit, regarding the compiler option: from a semantics point there option 1 and 3 are (more or less) "equal" [hint: if you find that it makes a difference in your code if you choose option1 or option3 ... that would be a good indication that your are doing something terribly wrong in your code).

尽管如此,一件可以有所作为的事情-如果您有一个依赖注入"构造函数,例如:

Nonetheless, the one thing that can make a difference - if you have a "dependency injection" constructor, like:

public YourClass() { this(new ArrayList<String>); }
YourClass(List<String> incomingList) { myList = incomingList; }

对于需要控制"的那些对象,这种解决方案是有意义的.从某种意义上说:您需要将模拟传递给您的类以启用单元测试.

This solution makes sense for those kinds of objects that you need to "control"; in the sense of: you require to pass mocks to your class to enable unit testing.

长话短说:

  • 如果可以的话,请选择选项1:使用最终
  • 如果需要依赖项注入,请使用option3
  • 除非您有充分的理由这么做,否则请避免使用option2

这篇关于在Java中初始化ArrayList字段的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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