I am a beginner. Can you please help me identify the mistake in the following program ?
import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayList li = new ArrayList<>();
li.add(1);
li.add(2);
li.add(3);
System.out.println(li.get(1));
int arr[] = new int[li.size()];
for(int i=0; i<li.size(); i++)
{
arr[i] = li.get(i);
}
for(int item:arr)
System.out.println(item);
}
}
While executing the above program, I get the following error :
Main.java:23: error: incompatible types: Object cannot be converted to int
arr[i] = li.get(i);
-
1Does this answer your question? Converting ArrayList to Array in javaChase– Chase2020年06月17日 06:10:55 +00:00Commented Jun 17, 2020 at 6:10
-
2What is a raw type and why shouldn't we use it?khelwood– khelwood2020年06月17日 06:13:31 +00:00Commented Jun 17, 2020 at 6:13
-
li is a list of strings, you have to use casting to make it into an integer.Carter– Carter2020年06月17日 06:50:11 +00:00Commented Jun 17, 2020 at 6:50
2 Answers 2
You are using raw ArrayList, so it contains Objects instead of Integers. You can't assign Object type to int type, hence you get the error when you try to save an Object type into intarray.
Pass a generic type argument to ArrayList so that compiler knows that li is an ArrayList that contains Integers.
Change
ArrayList li = new ArrayList<>();
to
ArrayList<Integer> li = new ArrayList<>();
Comments
You've not given the type for ArrayList in the declaration. So, that would be equivalent to ArrayList<Object>, meaning that any type of object can be added to arraylist. There are two ways you can fix this.
1. Declare the type in arraylist declaration.
ArrayList<Integer> li = new ArrayList<>();
2. Cast the object that that you fetch from list to an int type
for(int i=0; i<li.size(); i++)
{
arr[i] = (int)li.get(i);
}