Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-10-30 19:15:03
Original
384 people have browsed it

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!