我怎么能在同一时间将字符串和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)
更多推荐
发布评论