How to Generics ? is not object

时间:2017-12-18 08:31:52

标签: java generics casting

My intention is to cast a Object to (?) but how to do this? My Code:

<xsl:value-of select="ancestor-or-self::*[@header][1]/@header"/>

Which brings me following error

Wrong 2nd argument type. Found: 'java.lang.Object', required: '?'

Cast doesn't work:

Map<T,?> rawResult = initMap;
final T key = ...
final Object kryoResult = kryo.readClassAndObject(input);
rawResult.put(key,value);

Also this:

(?)value 

Isn't ? an Object? Because ? is "whatever... I don't care?"?

2 个答案:

答案 0 :(得分:1)

Because ? is "whatever... I don't care?"

That's wrong: <td><input type="radio" value="<?php echo $row['opt1']; ?>" /><br /></td> is I don't know rather than I don't care. That's why you can not add something to the map. because the map could also hold ? objects. So adding an String would cause an error.

Object

Also have a look at this question which explains wildcards Map<T, String> stringMap = new HashMap<>(); stringMap.put(key, "Value"); Map<T, ?> map = stringMap; // works Object value = map.get(key); // Object, because "map" doesn't know the types its holding map.put(key, "New Value"); // doesn't work, even though the map is holding stringValues in more detail.

答案 1 :(得分:-1)

在您声明接受?(unknown type)并尝试插入Object(known type)的情况下,编译器无法确认插入到列表中的对象类型,并且会产生错误

为了摆脱这种错误,我们需要使用一个帮助器方法,以便通过类型推断捕获通配符。

Map<T, ?> map = new HashMap<>();
T key = ...;
Object value = ...;
putInMap(map, key, value);

以及在地图中放置值的方法:

@SuppressWarnings("unchecked")
<K, V> void putInMap(Map<K, V> map, K key, Object value) {
    map.put(key, (V) value);
}

基本上,当您想要使用上限类型(对象以防无限制)迭代集合或Map时,会使用?(unknown type)

您可能需要查看此处的文档https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html

希望这有帮助。享受:)

相关问题