问题描述
我正在尝试编译以下代码:
私有字符串 dataToString(){映射数据 = (HashMap
) getData();字符串 toString = "";for( MyClass.Key key: data.keySet() ){toString += key.toString() + ":" + data.get(key);返回字符串;} 我在 for 行中收到一条错误消息:
<上一页>不兼容的类型找到:java.lang.Object必需:MyClass.Key
getData()
方法返回一个 Object
(但在这种情况下,返回的 Object
具有 HashMap
结构体).MyClass.Key
是我为我的应用程序创建的枚举(在另一个类文件 - MyClass
中).
当我在MyClass.java
中创建一个相同结构的foreach循环时,我没有遇到这个问题.
我做错了什么?
一种更有效的方法:
Mapdata = (HashMap) getData();StringBuffer sb = new StringBuffer();for (Map.Entry entry : data.entrySet()) {sb.append(entry.getKey());sb.append(":");sb.append(entry.getValue());}返回 sb.toString();
如果可能的话,定义getData"这样你就不需要演员表了.
I am trying to compile the following code:
private String dataToString(){
Map data = (HashMap<MyClass.Key, String>) 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<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();
StringBuffer sb = new StringBuffer();
for (Map.Entry<MyClass.Key,String> 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.
这篇关于如何在 Java 中使用 foreach 循环来遍历 HashMap 中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!