Casting Array in Java

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

Basic:

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.

How?

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

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

Advertisements

One Response to Casting Array in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: