karthick raja
karthick raja

Reputation: 21

How to downcast array of object type into an normal array?

I planned to convert an ArrayList into an normal array. After that i tried to downcast that object type into a normal array.But its showing that "Cannot convert from Object to int" at line 17.

package coll;

import java.util.ArrayList;
public class ToArray {

    public static void main(String[] args) {
        ArrayList a1=new ArrayList();
        a1.add(new Integer(2));
        a1.add(new Integer(8));
        a1.add(new Integer(7));
        a1.add(new Integer(6));
     System.out.println("the contents are"+ a1);
     Object ia[]=a1.toArray();
     int[] a=new int[5];
     for(Object i:ia)
     {
        a[i]=((Integer)ia[i]).intValue(); 
     }  
    }
}

Upvotes: 2

Views: 1515

Answers (3)

Oliver
Oliver

Reputation: 6250

First of all use Generics and always use Super Type to Reference An Object

Like This List<Integer> list = new ArrayList<Integer>();

Secondly there is no need to do this

list.add(new Integer(5));

You can directly do this list.add(5); the automatic Wrapping and Unwrapping will be done.

And about the Array thing do this,

int arr[] = new int[list.size()];

Iterator<Integer> i  =list.iterator();
int count =0 ;
while(i.hasNext())
{
   arr[count] = i.next();
   count++;
}

By Using Generics your ArrayList understands that it should accept Integers only. And you don't need to Downcast or Upcast Anything :D

Upvotes: 0

Gautam Savaliya
Gautam Savaliya

Reputation: 1437

Array takes only int value for indexing. In for loop you are trying to put object value for indexing so Downcast exception is coming.

Instead of :

for(Object i:ia){
     a[i]=((Integer)ia[i]).intValue(); 
}  

Use below code :

for(int i=0;i<ia.length;i++){
    a[i] = ((Integer) ia[i]).intValue();
}

Upvotes: 3

papercut
papercut

Reputation: 59

   public static void main(String[] args) {

        ArrayList a1 = new ArrayList();
        a1.add(new Integer(2));
        a1.add(new Integer(8));
        a1.add(new Integer(7));
        a1.add(new Integer(6));
        System.out.println("the contents are" + a1);

        Integer[] ia = (Integer[])a1.toArray(new Integer[a1.size()]);

        for (int i : ia) {
            System.out.println(i);
        }
    }

Upvotes: 1

Related Questions