Skip to main content

Have A Heart

Posted by editor on November 27, 2007 at 7:50 AM PST


Help the beginners figure out autoboxing

Sometimes the "Not-So-Stupid" question is a discussion-starter, with lots of ways the question can be answered. But other times, there really is something of a "correct" answer, and the existence of the question gets at the idea of why this answer isn't easier to find.

Consider today's not-so-stupid question, presented as
our Feature Article,
(Not So) Stupid Questions 20: Primitives and Collections. It cites a Sun Java SE 5.0 page that says:

As any Java programmer knows, you can't put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int).

Yet, a simple 10-line program shows it's trivially easy to add ints directly to an ArrayList. So what's the deal?

The seasoned developer knows that what's up is autoboxing, the automatic conversion by the compiler of integers to their primitive-wrapping object equivalents: ints become Integers, floats become Floats, etc. In fact, that's even the title of the documentation page that the above quote comes from. Problem is, the doc page kind of buries the idea of autoboxing in some too-clever code, and a discussion of performance considerations. It might have been better to take a paragraph and explicitly say something like "myArrayList.add(1) throws a compile-time exception before Java 5, and does what you expect it to in Java 5 and later."

And maybe that's something to talk about, that this is a feature that directly addresses problems developers have had with previous versions of Java, without considering what it looks like to the new developer who comes to the language without that experience, without presumptions or biases. Maybe it doesn't make sense to fresh eyes like it does to anyone who's done it the hard way. The conservative "no more language changes" crowd may see this as a problem, but then again, is autoboxing really unintuitive? Isn't the point to do what you would expect myArrayList.add(1) to do?

Hmmm... maybe not a stupid question at all...


In today's Weblogs,
David