简体   繁体   English

地图的getOrDefault <String, ?>

[英]getOrDefault for Map<String, ?>

Trying to getOrDefault for Map like: 尝试为Map获取或默认值:

String test = map.getOrDefault("test", "")

But it gives me an error "Required ? but got a String". 但这给了我一个错误“ Required?但有一个字符串”。 Anyway to get around this? 无论如何要解决这个问题?

The values of a Map<String, ?> could be of any type. Map<String, ?>可以是任何类型。

getOrDefault requires the second parameter to be of the same type as the values; getOrDefault要求第二个参数与值具有相同的类型; there is no value other than null which can satisfy this, because you don't know if that ? 除了null之外没有其他可以满足此要求的值,因为您不知道是否可以? is String , Integer or whatever. StringInteger或其他任何值。

Because you are only retrieving a value from the map, you can safely cast to a Map<String, Object> : 因为您只从映射中检索值,所以可以安全地强制转换为Map<String, Object>

Object value = ((Map<String, Object>) map).getOrDefault("key", "");

This is because you are not putting any value into the map which would make calls unsafe later; 这是因为您没有在映射中添加任何值,否则以后将使调用不安全。 and any value type can be stored safely in an Object reference. 并且任何值类型都可以安全地存储在Object引用中。

The implementation of this method returns the given default value (generics - can be any type) if not found (AKA null). 如果未找到,则此方法的实现返回给定的默认值(泛型-可以是任何类型)(AKA为null)。

  default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

documentation link attached: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V- 随附的文档链接: https : //docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-

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

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