java hashmap 遍历 for,如何在Java中使用foreach循环来遍历HashMap中的值?

在尝试将HashMap转换为String时遇到了编译错误。getData()方法返回一个Object,但期望的是MyClass.Key枚举类型。错误出现在for-each循环中,提示找到的是Object而不是MyClass.Key。解决方案是使用Map.Entry遍历并构建字符串,同时考虑修改getData()方法以避免强制转换。
摘要由CSDN通过智能技术生成

I am trying to compile the following code:

private String dataToString(){

Map data = (HashMap) getData();

String toString = "";

for( MyClass.Key key: data.keySet() ){

toString += key.toString() + ": " + data.get( key );

return toString;

}

I get an error in the for line that says:

incompatible types

found : java.lang.Object

required: MyClass.Key

The getData() method returns an Object (but in this case the Object returned has the HashMap structure). MyClass.Key is an enum that I have created for the purposes of my application (in another class file - MyClass).

When I created a foreach loop with the same structure in MyClass.java, I did not encounter this problem.

What am I doing wrong?

解决方案

A slightly more efficient way to do this:

Map data = (HashMap) getData();

StringBuffer sb = new StringBuffer();

for (Map.Entry entry : data.entrySet()) {

sb.append(entry.getKey());

sb.append(": ");

sb.append(entry.getValue());

}

return sb.toString();

If at all possible, define "getData" so you don't need the cast.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值