I am trying to create
ArrayList<int> myList = new ArrayList<int>();
in Java but that does not work.
Can someone explain why int
as type parameter does not work?
Using Integer
class for int
primitive works, but can someone explain why int
is not accepted?
Java version 1.6
Java generics are so different from C++ templates that I am not going to try to list the differences here. (See What are the differences between “generic” types in C++ and Java? for more details.)
In this particular case, the problem is that you cannot use primitives as generic type parameters (see JLS §4.5.1: "Type arguments may be either reference types or wildcards.").
However, due to autoboxing, you can do things like:
So that removes some of the pain. It definitely hurts runtime efficiency, though.