本文介绍了在 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>();

或者在 getter 中,像这样:

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.

推荐答案

第一个选项允许你做一个

The first option allows you to do a

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(或多或少)相等" [提示:如果您发现选择选项 1 或选项 3 对您的代码产生影响 ... 这将是一个很好的迹象,表明您在代码中做了一些非常错误的事情).

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:使用 final
  • 如果需要依赖注入,请使用 option3
  • 避免选择 2,除非你有充分的理由去做

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

08-20 15:29
查看更多