java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.String;

编程入门 行业动态 更新时间:2024-10-27 10:25:42
本文介绍了java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.String;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要将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;

本文发布于:2023-10-31 05:18:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   ClassCastException   lang   java   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!