Issue
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?
Solution
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.
Answered By - Paul Boddington