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?
Note: The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to loop through each entry of the hashmap.
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
There are generally five ways of iterating over a Map in Java.
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.
Change:
Map data = (HashMap<MyClass.Key, String>) getData();
to
Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();
The problem is that data.keySet()
returns a Collection<Object>
if data is just a Map
. Once you make it generic, keySet()
will return a Collection<MyClass.Key>
. Even better... iterate over the entrySet()
, which will be a Collection<MyClass.Key, String>
. It avoids the extra hash lookups.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With