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.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
Script_Junkie
  • 247
  • 2
  • 5
  • 15

2 Answers2

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()]);
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
  • 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 02:42
  • @Voo Only in Java 5 and later; before Java 5 it was necessary. – Sergey Kalinichenko Jul 29 '13 at 02:43
  • @dasblinkenlight I wasn't aware Java 5 was still used commonly. –  Jul 29 '13 at 02: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 02:48
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()]);