我需要将HashMap转换为String数组,以下是我的java代码
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]); } } }当我运行代码时,我得到以下 ClassCastException 。
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)推荐答案
toArray()返回 Object [] ,无论泛型如何。您可以使用重载的变体:
toArray() returns an Object[], regardless of generics. You could use the overloaded variant instead:
String[] str = map1.keySet().toArray(new String[map1.size()]);或者,因为 Set 's toArray 方法不保证订单,你使用数组的所有内容都是打印出值,你可以迭代 keySet()直接:
Alternatively, since a Set's toArray method gives no guarantee about the order, and all you're using the array for is printing out the values, you could iterate the keySet() directly:
for (String str: map1.keySet()) { System.out.println(str); }编辑:只是为了完成图片,在Java 8中, foreach 方法可用于使代码更优雅:
Just to complete the picture, in Java 8, the foreach method can be used to make the code more elegant:
map1.keySet().forEach(System.out::println);更多推荐
java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.String;
发布评论