Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

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.

share|improve this question

marked as duplicate by Pshemo, Don Roby, Luiggi Mendoza, dasblinkenlight, Richard Sitze Jul 29 '13 at 4:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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()]);
share|improve this answer
2  
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 Jul 29 '13 at 2:42
    
@Voo Only in Java 5 and later; before Java 5 it was necessary. – dasblinkenlight Jul 29 '13 at 2:43
    
@dasblinkenlight I wasn't aware Java 5 was still used commonly. – user1181445 Jul 29 '13 at 2:44
    
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 – Voo Jul 29 '13 at 2:48

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()]);
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.