Casting Array in Java

Casting an array directly throw ClassCastException. This is how I get around it.


import java.util.ArrayList;

ArrayList<MyObject> tmp = new ArrayList<MyObject>();

// insert data in to tmp

// this will prompt and ask for casting

MyObject[] tmpArray = tmp.toArray();

// this will throw ClassCastException

MyObject[] tmpArray (MyObject[]) tmp.toArray();

Why? Because toArray() returns a type of Object[] and it requires type casting.


MyObject[] tmpArray (MyObject[]) tmp.toArray(new MyObject[tmp.size()]);

I guess it should be the same for other dynamic list types.