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.