Home  >  Article  >  Java  >  Why does `List.toArray()` throw a `ClassCastException` when used with a `List`?

Why does `List.toArray()` throw a `ClassCastException` when used with a `List`?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 19:15:03361browse

Why does `List.toArray()` throw a `ClassCastException` when used with a `List`?

Java: (String[])List.toArray() Gives ClassCastException

When using List.toArray() with a list of strings, one might expect to receive an array of strings. However, this can often result in a ClassCastException.

This occurs because toArray() returns an Object[], not a String[]. This is because generics are not available at runtime. When a list is created as List, it is stored as a List. At runtime, there is no information about the type of objects in the list. Thus, toArray() must return an Object[].

To obtain a String[] from a list of strings, use toArray(new String[v2.size()]). This will allocate a String[] of the appropriate size and populate it with the strings from the list.

The above is the detailed content of Why does `List.toArray()` throw a `ClassCastException` when used with a `List`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn