1

I have a class

public class ABC {
    public int i;
    public float f;

    public ABC(int d1,float d2) {
        i=d1;
        f=d2;
    }
}

I have created a ArrayList of ABC object .

    ArrayList<ABC> list = new ArrayList<ABC>();
    ABC abc1=new ABC(1,1.0f);
    ABC abc2=new ABC(2,2.0f);
    list.add(abc1);
    list.add(abc2);

Now I want to convert the ArrayList into array with toArray() method, but this Method returns Object[];.

Now I can typecast elements of Object[] one by one into ABC type object and create ABC[];,

but Is there any other way to typecast the Object[] into ABC[] in one command ? Something like this

    ABC[] array=(ABC[])list.toArray();

though this command throws this exception

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; can not be cast to [LABC;**

Any Help

Scarecrow
  • 4,057
  • 3
  • 30
  • 56
  • 1
    Cast does not change the class of an object, and the class of the array is `Object[]`. You can use System.arraycopy to copy the array into one of the desired class. – Hot Licks Feb 18 '13 at 17:50

2 Answers2

4

The List interface has a toArray method that returns the generically-typed array, so you can useArrayList's implementation of that:

ABC[] array = new ABC [list.size()]
array = list.toArray(array);
user
  • 3,058
  • 23
  • 45
0

toArray() documentation

ABC[] array = list.toArray(new ABC[list.size()])
user
  • 3,058
  • 23
  • 45
Rick Mangi
  • 3,761
  • 1
  • 14
  • 17