Susie Susie - 3 months ago 11
Java Question

Create a List of primitive int?

Is there a way to create a list of primitive int or any primitives in java like following?

List<int> myList = new ArrayList<int>();


It seems I can do
List myList = new ArrayList();


and add "int" into this list. But then this would mean I can add anything into this list.

Is my only option, creating an array of int and converting it into a list or creating a list of Integer objects?

Answer

In Java generic type arguments must be objects. 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