Java collections. Why no Primitive Types?

user485498 picture user485498 · Jan 4, 2011 · Viewed 24.4k times · Source

Possible Duplicate:
storing primitive values in a java collection?

My Java textbook says elements of a collection, for example ArrayList, cannot be primitive types. Is there a reason for this? I mean did someone at Sun decide on this or is there some barrier against doing it? I understand my example half-answers my question since ArrayList requires an object and primitives are not objects. But then I think why can't they have primitive types as well?

Answer

Daniel Earwicker picture Daniel Earwicker · Jan 4, 2011

is there some barrier against doing it?

You could write near-identical versions of ArrayList that were tailor made to store one of the non-class types, e.g. IntegerArrayList and so on. The barrier against this is that there would be an explosion of such classes, as you'd multiply the number of primitive types by the number of collection types. In order to keep the standard collection framework manageable, this was ruled out.

To solve this more neatly in the language, you'd need generics to allow primitive types to serve as type parameters, and improve the interaction between arrays and generics.