I need convert HashMap to a String array, follow is my java code
import java.util.HashMap;
import java.util.Map;
public class demo {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("1", "1");
map1.put("2", "2");
map1.put("3", "3");
String[] str = (String[]) map1.keySet().toArray();
for(int i=0; i<str.length;i++) {
System.out.println(str[i]);
}
}
}
when I run the code, I get the following ClassCastException
.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at demo.main(demo.java:17)
Best Answer
toArray()
returns anObject[]
, regardless of generics. You could use the overloaded variant instead:Alternatively, since a
Set
'stoArray
method gives no guarantee about the order, and all you're using the array for is printing out the values, you could iterate thekeySet()
directly:EDIT: Just to complete the picture, in Java 8, the
foreach
method can be used to make the code more elegant: