我应该在声明时实例化集合字段吗?

Should I instantiate collection field on declaration?

在声明时实例化集合字段是一种好习惯吗?例如:

class A {
    private List<String> list = new ArrayList<>();

    public List<String> getList() {
        return list;  
    }

    public setList(List<String> list) {
        this.list = list;
    }
}

我需要它的原因是避免像这样检查 null:

if (a.getList() != null)

最好尽可能避免使用 null 值。您还可以将字段设为 final,这样您就知道它永远不会 null 有一些注释可以让您跟踪该值不能为 null。

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

@NotNull
public List<String> getList() {
    return list;  
}

如果您以后再这样做

if (a.getList() != null) // your IDE can tell you this is always true.

意见不一,但在这种情况下,我肯定会争辩 :空 collections 比可空 empty-able collections.

在那里初始化也意味着你可以使字段 final 带来一些好处,虽然在这里你必须让你的 setList() 而不是调用 clear()addAll() 新物品。因此,单独可能没有太大好处,但在其他情况下它有优势...

我认为启动对象的更好位置是 class.
Constructor 综合解释:Should I instantiate instance variables on declaration or in the constructor?

Instantiating object in a constructor

使用您显示的特定代码,setList() 可以设置一个 null 值,因此您无法删除空检查。但是,我建议您将 setter 更改为 1) 拒绝空值,或 2) 设置 Collections.emptyList() 而不是空值,或 3) 设置新的 ArrayListLinkedList null 个。 空值总是很难处理,对于集合来说更是如此。许多最佳实践建议禁止空集合。并且我衷心同意。

更改此类行为意味着您需要查看 getList () 的所有调用站点并检查此类更改不会破坏它。如果是,则需要更改解决方案或调整客户端代码。