Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store int in ArrayList and get it back to primitive variable int - Java

I'm getting an error, and can't find out how to solve it.

I add a int to an ArrayList.

int n = 1;
ArrayList list = new ArrayList();
list.add( n );

Further down, I try to put it back in another int:

grid[ y ][ x ] = list.get(0);

I also tried this:

grid[ y ][ x ] = (int) list.get(0);

But it doesn't work, I get this error:

found   : java.lang.Object
required: int
grid[ y ][ x ] = (int)list.get(0);
                              ^

I hope someone can help me.

like image 269
Chris Avatar asked Oct 11 '11 13:10

Chris


2 Answers

(Integer)list.get(0) will do the trick. Auto-unboxing will then convert it to an int automatically

like image 50
Ingo Kegel Avatar answered Oct 20 '22 16:10

Ingo Kegel


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.

like image 40
Michael Borgwardt Avatar answered Oct 20 '22 17:10

Michael Borgwardt