2

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(); 
     }  
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172

3 Answers3

3

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();
}
Gautam Savaliya
  • 1,403
  • 2
  • 20
  • 31
  • ya.. Thanks.. I'm just a beginner. I'm having a doubt. For each can be used for iterating array values.. here i'm using 'foreach' to iterating an array containing object type. cant we use for each?? – karthick raja Sep 30 '14 at 01:31
  • You can use foreach loop to iterate arraylist containing object but you are trying to assign value to array also same time. – Gautam Savaliya Sep 30 '14 at 04:04
1
   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);
        }
    }
papercut
  • 59
  • 2
0

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

Oliver
  • 6,152
  • 2
  • 42
  • 75
  • Please Refer to documentation. You get to learn a lot by reading documentation. http://docs.oracle.com/javase/6/docs/api/java/util/List.html – Oliver Sep 29 '14 at 05:28
  • Thanks alot. As a beginner now only i came to know about the importance of generics.great job.. – karthick raja Sep 30 '14 at 01:42