如何将元素添加到Java通用通配符列表(How to add element to Java Generic Wildcard List)

编程入门 行业动态 更新时间:2024-10-27 10:29:42
如何将元素添加到Java通用通配符列表(How to add element to Java Generic Wildcard List)

我怎么能在同一时间将字符串和int值添加到HashMap?

HashMap<String,?> map =new HashMap<>(); map.put("sss", "str"); map.put("sss", 1);

Android SharedPreferences.getAll()方法如何做到这一点?

错误信息

Found 'java.lang.String', required: '?'

How could I add string and int value to a HashMap same time ?

HashMap<String,?> map =new HashMap<>(); map.put("sss", "str"); map.put("sss", 1);

How Android SharedPreferences.getAll() method did this?

Error message

Found 'java.lang.String', required: '?'

最满意答案

您不能向Map<String, ?>添加任何内容(除了文字null ),因为它可能是错误的类型。 例如:

Map<String, Long> longMap = ...; Map<String, ?> wildcardMap = longMap; wildcardMap.put("", ""); // Compiler error! // but if it did work, the following would be a runtime error: Long value = longMap.values().iterator().next();

还记得? 是速记? extends Object ? extends Object ; 首字母缩略词PECS告诉你, extends东西是生产者 ,而不是消费者 。 因此,您无法在其实例上调用使用者方法(除非您传递null )。

如果要将异构值放入映射中,则值类型必须是类型的公共超类。

Map<String, Object> mapForBoth = ... mapForBoth.put("key1", "string"); mapForBoth.put("key2", 1);

(实际上, Serializable是String和Integer一个更具体的常见超类;它取决于你是否是更好的值类型)

You can't add anything (other than literal null) to a Map<String, ?>, because it could be the wrong type. For example:

Map<String, Long> longMap = ...; Map<String, ?> wildcardMap = longMap; wildcardMap.put("", ""); // Compiler error! // but if it did work, the following would be a runtime error: Long value = longMap.values().iterator().next();

Remember that ? is a shorthand for ? extends Object; and the acronym PECS tells you that something which extends is a producer, not a consumer. So, you can't invoke a consumer method on an instance of it (unless you pass null).

If you want to put heterogeneous values into the map, the value type has to be a common superclass of the types.

Map<String, Object> mapForBoth = ... mapForBoth.put("key1", "string"); mapForBoth.put("key2", 1);

(Actually, Serializable is a more specific common superclass of String and Integer; it's up to you as to whether that's a better value type)

更多推荐

本文发布于:2023-08-04 09:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   如何将   元素   列表   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!