Store int in ArrayList and return it to primitive int variable - Java

I get an error message and cannot find out how to solve it.

I add int to ArrayList.

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

Next, I try to return it to another int:

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

I also tried this:

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

But this will not work, I get this error:

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

Hope someone can help me.

+7
source share
4 answers

Use a type parameter, not a raw ArrayList :

 ArrayList<Integer> list = new ArrayList<Integer>(); 

The error you get is that you cannot drop Object to int , autoboxing is unlocked there. You can pass it to Integer and then pass it autounboxed to int , but using a type parameter is a much better solution.

+10
source

Use ArrayList<Integer> . When you do list.get() , you will get an Integer , which you can call intValue() to get int

+7
source

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

+3
source

The main difference between Array-list and Arrays is that Array-list can only store objects in it, but not primitive data types (in your case, an integer). therefore, to solve this problem, we use ArrayList<Integer> list = new ArrayList<Integer>(); Thanks.

0
source

Source: https://habr.com/ru/post/899053/


All Articles