Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: (String[])List.toArray() gives ClassCastException

The following code (run in android) always gives me a ClassCastException in the 3rd line:

final String[] v1 = i18nCategory.translation.get(id); final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1)); String[] v3 = (String[])v2.toArray(); 

It happens also when v2 is Object[0] and also when there are Strings in it. Any Idea why?

like image 698
Gavriel Avatar asked Apr 16 '11 23:04

Gavriel


People also ask

What does toArray return in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

Why does toArray return object?

Because arrays have been in Java since the beginning, while generics were only introduced in Java 5. And the List. toArray() method was introduced in Java 1.2, before generics existed, and so it was specified to return Object[] .


1 Answers

This is because when you use

 toArray()  

it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because the toArray method only gets a

List  

and not

List<String> 

as generics are a source code only thing, and not available at runtime and so it can't determine what type of array to create.

use

toArray(new String[v2.size()]); 

which allocates the right kind of array (String[] and of the right size)

like image 172
MeBigFatGuy Avatar answered Sep 19 '22 01:09

MeBigFatGuy