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

JavaListClasscastexceptionToarray

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

You are using the wrong toArray()

Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.

To fix your problem, call toArray(T[]). In your case,

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

Note that the genericized form toArray(T[]) returns T[], so the result does not need to be explicitly cast.

Solution 3 - Java

String[] v3 = v2.toArray(new String[0]); 

also does the trick, note that you don't even need to cast anymore once the right ArrayType is given to the method.

Solution 4 - Java

Using toArray from the JDK 11 Stream API, you can solve the more general problem this way:

Object[] v1 = new String[] {"a", "b", "c"}; // or array of another type
String[] v2 = Arrays.stream(v1)
    .<String>map((Object v) -> v.toString()).toArray(String[]::new);

Solution 5 - Java

String[] str = new String[list.size()];
str = (String[]) list.toArray(str);

Use like this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGavrielView Question on Stackoverflow
Solution 1 - JavaMeBigFatGuyView Answer on Stackoverflow
Solution 2 - JavaDilum RanatungaView Answer on Stackoverflow
Solution 3 - JavaHopefullyHelpfulView Answer on Stackoverflow
Solution 4 - JavaMarioView Answer on Stackoverflow
Solution 5 - JavaMakNeView Answer on Stackoverflow