0

Have a function that takes an Object type as parameter, I want to use this function by passing a Map<String, String> variable. Unfortunately got complaints for that. Is there a way to cast Map<String, String> to Object? I thought any type of class can be automatically casted to Object since Object is the super class of everything.

This is the code:

private GeometryWithTags getRouteGeometryWithTags(Route route)
{
    Map<String, Map<String, String>> edgesTags = new HashMap<>();
        Iterator<Edge> edgeIterator = route.iterator();
        while (edgeIterator.hasNext())
        {
            Edge edge = edgeIterator.next();
            edgesTags.put(new Long(edge.getIdentifier()).toString(), edge.getTags());
        }
        return new GeometryWithTags(route.asPolyLine(), edgesTags);
    }

error: incompatible types: Map> cannot be converted to Map return new GeometryWithTags(route.asPolyLine(), edgesTags);

Yitian Zhang
  • 314
  • 1
  • 3
  • 18
daydayup
  • 2,049
  • 5
  • 22
  • 47

1 Answers1

0

The reason Map<String, Map<String, String>> can't be converted to Map<String, Object> is that the latter can do things the former can't. Consider

Map<String, Map<String, String>> myStringMap = new HashMap<>();
Map<String, Object> myObjectMap = myStringMap; // Not allowed, but suppose it were
myObjectMap.put("key", new Integer(10));
// Now myStringMap contains an integer,
// which is decidedly *not* a Map<String, String>

If this were allowed, then the .put call would fail at runtime, so this sort of situation is disallowed by the type system. If GeometryWithTags is a class you control and it actually never adds anything to the map, you should use the PECS pattern

GeometryWithTags(Map<String, ? extends Object> map) { ... }

Now we have a map that can have any value type, but we're guaranteed that we can't add anything (since the ? could be incompatible with the added value).

If GeometryWithTags needs to be able to modify the map, or if you don't have control over the class, then you need to actually make a Map<String, Object> initially.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116