In this case where you declared to accept ?(unknown type)
and trying to insert Object(known type)
, the compiler is not able to confirm the type of object that is being inserted into the list, and an error is produced.
To get rid of such error we need to use a helper method so that the wildcard can be captured through type inference.
Map<T, ?> map = new HashMap<>();
T key = ...;
Object value = ...;
putInMap(map, key, value);
and method for putting value in map:
@SuppressWarnings("unchecked")
<K, V> void putInMap(Map<K, V> map, K key, Object value) {
map.put(key, (V) value);
}
Basically, ?(unknown type)
is used when you want to iterate through the collection or Map with upper bounded type(Object in case not bounded).
You might want to go through the documentation here https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html.
Hope this help. Enjoy :)