Question

Why the below code fail to execute though it wont detect as an error from the IDE. And it will compile fine.

 ArrayList<String> a = new ArrayList<String>();
    a.add("one");
    a.add("two");
    a.add("three");
    String [] b = (String[])a.toArray();
    for(int i =0;i<b.length;++i){
        System.out.println(b[i]);
    }

But it will give the following error.

nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Can anyone give a clear explanation? The same problem has been asked before and some solutions has been provided. But a clear explanation of the problem will be much appreciated.

Was it helpful?

Solution

You should simply do:

String[] b = new String[a.size()];
a.toArray(b);

You're getting the error because toArray() returns Object[] and this cannot be cast down to String[].

OTHER TIPS

You need to mention the type of array, else by default, toArray() would return an array of Object which can't be simply casted to String[]. If you specify the type, the overloaded toArray(T[]) would be called, returning the type of array mentioned as the parameter.

String [] b = a.toArray(new String[]{});

a.toArray() is creating an Object[] rather than a String[] and hence the typecast is failing.

 String[] b = a.toArray(new String[a.size()]);

Refer to the javadocs for the two overloads of List.toArray

Have a look at the JavaDoc, toArray() returns a Object[] array, which cannot be downcast to String[].

You'll need this method instead - the reason being that generics are erased at runtime, so the JVM won't know that your ArrayList used to be one that contained String's:

String [] b = a.toArray( new String[] {} );

Cheers,

(Something that might help in now/future.)

Since 1.5 you are are able to do this way:

for(String output : a) { // Loops through each a (which is a String)
 System.out.println(output); // As it is a String list we can just print it
}

This more more readable and may come in handy to know.

Output:

one
two
three
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top