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.
This is because the parameterless toArray
produces an array of Object
s. You need to call the overload which takes the output array as the parameter, and pass an array of String
s, 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()]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With