Java: Casting to Array

OK, here’s the problem:

I want to convert a List to an Integer[]:

List<Integer> intList = ...
Integer[] intArray = (Integer[]) intList.toArray();

throws: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

This code doesn’t work, because of type incompatibility. The method toArray() returns an Object[] array but I want to have an Integer[] array instead. The solution is a little bit ugly:

List<Integer> intList = ...
Integer[] intArray =  intList.toArray(new Integer[0]);

It’s interesting, I never stumbled over this issue before, however I want toArray() to work as expected for generic types and already returning an integer array :/

Advertisements

0 Responses to “Java: Casting to Array”



  1. Leave a Comment

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: