5
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.

0

2 Answers 2

5

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()]);
Sign up to request clarification or add additional context in comments.

4 Comments

Isn't the cast superfluous here? Don't have a compiler on hand but I don't see why not. Also a link to some explanation about co/contra variance would make the answer complete I think.
@Voo Only in Java 5 and later; before Java 5 it was necessary.
@dasblinkenlight I wasn't aware Java 5 was still used commonly.
Oh right that function already existed before java 5, so yes it makes a difference there. Although I hope nobody is really using java 1.4 anymore
0

You are attempting to cast from a class of Object[]. The class itself is an array of type Object. You would have to cast individually, one-by-one, adding the elements to a new array.

Or you could use the method already implemented for that, by doing this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.