Reference: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
\"If your program tries to autounbox null, it will throw a NullPointerEx
It was never intended, with the introduction of autoboxing, that it replace the primitives. In most places primitives are what you want. If you want to start using the reference types because "it got java closer to be truly object-oriented" then that's your call, but as you are discovering, there are disadvantages with that approach. Performance will be another issue.
Autoboxing (and autounboxing) is there to help with the transitions between code that uses primitives (the majority) and the code that has to use reference types (rare). Of the reference types, Boolean is undoubtedly the rarest, since its small number of instances mean it's almost never worth putting in a Collection.
In summary: if the reference types are causing you trouble, don't use them. But don't say 'autoboxing is bad" just because they turned out not to be helpful in your situation.
Your issue is with autounboxing, not autoboxing. I think autounboxing is evil for more significant reasons:
Consider this:
Integer i = new Integer(1);
Integer i2 = new Integer(12);
System.out.println(i == 10 || i != i2);
One ==
unboxes and the other doesn't.
Unboxing on operators (as opposed to assignments) was a mistake in my view (given the above - it is just not Java). Boxing, however, is very nice.
I've seen at least one case where the null
value is useful. Lots of data objects in webservices have nullable boolean fields. Sometimes the user neglects to include a value. In this case you want to be able to discern the lack of a value from a default value. Previously, people would write getX
, setX
, and isXSet()
methods, where isXSet
returns false until someone calls setX
. Now it's possible to make X
be a nullable type and it's clear that it wasn't set if getX
returns null
.