什么是 NetBeans "Return of Collection Field" 可选警告?

What is the NetBeans "Return of Collection Field" optional warning?

我正在 NetBeans 中启用尽可能多的可选警告,以期成为更好的编码员。其中之一是 "Return of Collection Field"。它的整个描述是"Warns about return of collection fields"。 The Wiki wasn't any more helpful.

这是什么意思?它怎么会对 return 一个 collection 字段有害?

Java 中的许多集合 class 是可变的,例如 ArrayListHashSetTreeMap。这意味着您可以更改它们(例如,通过添加项目或清除它们)。这意味着您在编写不可变 class 时必须小心,您的 getter 用于集合字段 returns a copy.

例如,您应该这样做:

public final class Example {

    private final List<Integer> list;

    public Example(List<? extends Integer> list) {
        this.list = new ArrayList<Integer>(list);
    }

    public List<Integer> getList() {
        return new ArrayList<Integer>(list);
    }
}

如果 getList() 只是说 return list; 调用者将引用私有字段 list 本身,因此对返回对象所做的任何更改都会改变Example

当您写类似 return list; 的内容时,该警告可能会告诉您。我的建议是保留该可选警告,因为不假思索地编写 return list; 非常容易,结果可能会非常混乱。

@沙华金 为防止这种情况,您可以使用

public List<Integer> getList() {
    return Collections.unmodifiableList(list);
}