Create a List of primitive int?

Susie picture Susie · Aug 2, 2013 · Viewed 227.6k times · Source

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

Kevin Bowersox picture Kevin Bowersox · Aug 2, 2013

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