In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object
they cannot be used as generic type arguments for a parametrized type.
Instead use the Integer
class which is a wrapper for int
:
List<Integer> list = new ArrayList<Integer>();
If your using Java 7 you can simplify this declaration using the diamond operator:
List<Integer> list = new ArrayList<>();
With autoboxing in Java the primitive type int
will become an Integer
when necessary.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
So the following is valid:
int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);
System.out.println(list.get(0)); //prints 1