0

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);
Littm
  • 4,923
  • 4
  • 30
  • 38
  • 1
    Does this answer your question? [Converting ArrayList to Array in java](https://stackoverflow.com/questions/9929321/converting-arraylist-to-array-in-java) – Chase Jun 17 '20 at 06:10
  • 2
    [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – khelwood Jun 17 '20 at 06:13
  • li is a list of strings, you have to use casting to make it into an integer. – Carter Jun 17 '20 at 06:50

2 Answers2

4

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<>();
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

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);
   }