简体   繁体   English

Java Cast地图 <String, String> 反对

[英]java cast Map<String, String> to Object

Have a function that takes an Object type as parameter, I want to use this function by passing a Map<String, String> variable. 有一个将Object类型作为参数的函数,我想通过传递Map<String, String>变量来使用此函数。 Unfortunately got complaints for that. 不幸的是对此有所抱怨。 Is there a way to cast Map<String, String> to Object ? 有没有一种方法可以将Map<String, String>Object I thought any type of class can be automatically casted to Object since Object is the super class of everything. 我认为任何类型的类都可以自动转换为Object,因为Object是一切的超类。

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); 错误:类型不兼容:无法将Map>转换为Map返回新的GeometryWithTags(route.asPolyLine(),edgeTags);

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. 无法将Map<String, Map<String, String>>转换为Map<String, Object>是后者可以做前者不能做的事情。 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. 如果允许这样做,则.put调用将在运行时失败,因此类型系统不允许这种情况。 If GeometryWithTags is a class you control and it actually never adds anything to the map, you should use the PECS pattern 如果GeometryWithTags是您控制的类,并且实际上从不向地图添加任何内容,则应使用PECS模式

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. 如果GeometryWithTags需要能够修改地图,或者您无法控制该类,则实际上需要最初制作Map<String, Object>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM