Store int in ArrayList and get it back to primitive variable int - Java
Use ArrayList<Integer>
. When you do list.get()
you will get an Integer
which you can call intValue()
on to get an int
(Integer)list.get(0)
will do the trick. Auto-unboxing will then convert it to an int
automatically
Use a type parameter rather than the raw ArrayList
:
ArrayList<Integer> list = new ArrayList<Integer>();
The error you get is because you cannot cast an Object
to int
, autoboxing breaks down there. You could cast it to Integer
and then have it autounboxed to int
, but using the type parameter is a much better solution.