Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Object array into String array throws ClassCastException [duplicate]

List<String> list = getNames();//this returns a list of names(String).

String[] names = (String[]) list.toArray(); // throws class cast exception.

I don't understand why ? Any solution, explanation is appreciated.

like image 979
Script_Junkie Avatar asked Jul 29 '13 02:07

Script_Junkie


1 Answers

This is because the parameterless toArray produces an array of Objects. You need to call the overload which takes the output array as the parameter, and pass an array of Strings, like this:

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

In Java 5 or newer you can drop the cast.

String[] names = list.toArray(new String[list.size()]);
like image 142
Sergey Kalinichenko Avatar answered Sep 20 '22 07:09

Sergey Kalinichenko