Can someone tell me what is wrong with the following code?
Set<String> cmds = *a method call that returns a Set<String>*
String[] cmdarr = (String[]) cmds.toArray();
int i;
for(i=0; i<cmdarr.length;i++){
System.out.println(cmdarr[i]);
It gave the following error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at a.jim.Test.main(Test.java:79)
Thanks in advance!
The
Setitself doesn’t have any type information about its elements available at runtime; the type parameter<String>is erased during compilation. So, thetoArray()method always creates an array of typeObject[].You can pass an array to the method and have the contents of the set copied into it:
The the array you pass in is too small, a new one with the same component type will be created using reflection, but that is not as efficient as passing in one of the correct size.