什么是NetBeans的“退货字段"?可选警告? [英] What is the NetBeans "Return of Collection Field" optional warning?
问题描述
我正在尽我所能在NetBeans中启用尽可能多的可选警告,以试图成为更好的编码器.其中之一是返回收款字段".它的整个描述是关于回收字段的警告". Wiki不再有用.
这是什么意思?返回收集字段有何危害?
Java中的许多集合类(例如ArrayList
,HashSet
和TreeMap
)都是可变的.这意味着您可以更改它们(例如,通过添加项目或清除它们).这意味着在编写一个不可变的类时,您必须小心,收集类的getter返回一个 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;
非常容易,而无需考虑,结果可能会造成混乱.
I'm enabling as many optional warnings in NetBeans as I can, in an attempt to become a better coder. One of them is "Return of Collection Field". Its entire description is "Warns about return of collection fields". The Wiki wasn't any more helpful.
What does this mean? How can it be harmful to return a collection field?
Many collection classes in Java such as ArrayList
, HashSet
and TreeMap
are mutable. This means that you can change them (by adding items or clearing them, for example). This means that you have to be careful when writing an immutable class that your getter for a collection field returns a copy.
For example, you should do this:
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);
}
}
If getList()
had simply said return list;
the caller would have had a reference to the private field list
itself, so any changes made to the returned object would mutate the instance of Example
.
That warning presumably tells you when you write something like return list;
. My advice would be to keep that optional warning on, as it's extremely easy to write return list;
without thinking, and the results can be very confusing.
这篇关于什么是NetBeans的“退货字段"?可选警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!