I remember that when I discovered Java and realized that objects retrieved
from collections needed to be downcast to the proper type, a painful decade of
hard-learned C++ pitfalls immediately caused me to be worried about the
potential unsafe aspect of this feature. I was pretty sure that I would
soon be spending a lot of time debugging reams of ClassCastExceptions
because of this "oversight". I wasn’t alone.
But we were all wrong.
We know now that such errors are very rare and nobody would think of
criticizing Java on this criterion any more.
A recent discussion about unboxing made me wonder if we were not making the
same mistake again.
It started with this innocent-looking piece of code:
Map<String, Integer> lookupTable = new HashMap<String, Integer>();
int value = lookupTable.get("foo");
which, as of JDK 5, will throw a NullPointerException (a behavior
which, in my opinion, is a Good Thing, and was almost unanimously passed by the
JSR 201 Experts Group with a vote count of 19-1).
Do you remember the reaction of the community when the early proposals for
boxing and unboxing were unveiled? If I recall correctly, everybody was
afraid of one very simple thing: performance.
We all thought that all this hidden boxing/unboxing that silently translates
simple pieces of code into expensive conversions would take a heavy toll on the
performances of our applications, and so we all prudently stayed away from it
"just in case". I’m still wary of boxing overall, but I have to say the
performance concern has all but faded from my mind. However, I do
occasionally find myself tripping on some unplanned side effect of the
specification, such as the one mentioned above.
It’s not very often, but once in a while,
the crowd is not that wise.