I've seen this kind of declaration in jdk 8 sample:
Map<String, ?> map = new HashMap<>(3);//OK
But when I tried to add value to "map", I didn't succeed:
map.put("abc", Optional.of(5)); map.put("kk", "xyz");
Both fail to compile. I wish to know:
(1) What does "?" indicate in Map declaration above?
(2) How to give values to this "map"?
? is called wildcard generic type.It can be used with any type, but you need to specify type fist as Map is an abstract class.
for you to give value to this map its either you use Upper bound or Lower bound.
The following are guidelines when using upper bound or lower bound
? extends Type - is used for read access only ? super Type - is used for write access only.
PECS in short Produces(write acccess) -uses Extends while Consumes(read access) - uses Super
Map<String, ? super Object> map = new HashMap<>(3);//OK map.put("abc",Optional.of(5)); map.put("kk","xyz"); map.forEach((k,v)->System.out.println(k+"/t"+v));
kk xyz abc Optional Process finished with exit code 0
Unbounded wildcard ?
List<?> l = new ArrayList<String>();
Wildcard with an upper bound ? extends type
List<? extends Exception> l = new ArrayList<RuntimeException>();
Wildcard with a lower bound ? super type
List<? super Exception> l = new ArrayList<Object>();