Re: Mutable Objects and Thread Boundaries
Lew wrote:
Be very careful with auto(un)boxing.
Alan Gutierrez wrote:
Why?
Because of the risk of exceptions or surprising results.
I asked my friend Google and it said:
http://fupeg.blogspot.com/2007/07/auto-unboxing-in-java.html
I don't see how in the example code in this thread, auto unboxing
triggers an NPE.
public List<Integer> list(int i) {
List<Integer> list = new ArrayList<Integer>();
list.add(i);
return list;
}
Other than the silliness of it, what is wrong with the above? (Or maybe
I reduced the example too much?)
That is not an example of the risk for NPE. Nor of the risk of autoboxing.
You need a different example.
NPE is not the only risk. Yes, it is a risk when autounboxing, because the
wrapper might be null, and unboxing will raise NPE in that case. But you can
also confuse the compiler if you mix autoboxing and varargs in certain ways.
I've also seen cases where a class refactored a method that took a 'long'
argument to one that took a 'Long' but forgot to refactor the corresponding
method in the interface implemented by the class.
Auto(un)boxing hides an operation that sometimes produces different behaviors
than one expects. Therefore one must be very careful with it.
IMHO it's not a terribly useful feature. It hides type assertions, which
diminishes one of Java's great strengths. I prefer to do all my (un)boxing
explicitly. What, I'm going to sprain my fingers with the extra typing? It's
worth the effort to improve the self-documenting nature of my code, and to
obviate the occurrence of those bugs.
--
Lew