GoO-Rung Aadii
GoO-Rung Aadii

Reputation: 21

changing arraylist to array in java

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

Upvotes: 0

Views: 101

Answers (2)

Aashish Shrestha
Aashish Shrestha

Reputation: 25

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

Upvotes: 0

Yousaf
Yousaf

Reputation: 29334

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

Upvotes: 4

Related Questions