-2

Does anyone have any help with this error?

error: incompatible types: Object cannot be converted to String

I am passing a HashMap into a function with the intention of iterating through its keyset and storing them into a list for ordering, here is my code

public HashMap mapReorder(HashMap map) {

    /* Clear the list ready for input */
    mapList.clear();

    /* Iterate through the keys in the map */

    for(String keys : map.keySet()) {
        double mapKey = keys.getValue();
        mapList.add(mapKey);
    }

    /* Sorting the order by ascending value (Internal Frequency Rank) */
    Collections.sort(mapList);

    /* Populating HashMap with ordered list */
    for(double frequencies : mapList) {
        orderedMap.put(keys , frequencies);
    }

    return null;
}
hoefling
  • 59,418
  • 12
  • 147
  • 194

2 Answers2

2

the line with for(String keys : map.keySet()) is causing the error.

Map.keySet() returns a Set<Object> and not a Set<String> because you're using rawTypes (HashMap). So change either the line to:

for(Object keys : map.keySet())

or change the signature of your method to following:

public HashMap<String, ValueType> mapReorder(HashMap<String,ValueType> map){

where ValueType is the type of value stored in your map

Lino
  • 19,604
  • 6
  • 47
  • 65
-2

I am passing a hashmap into a function with the intention of iterating through its keyset and storing them into a list for ordering

HashMap is not ordered. So you better use TreeMap which is sorted according to natural ordering of its keys.

return new TreeMap(map)
ThomasEdwin
  • 2,035
  • 1
  • 24
  • 36