request:
The value of Map is List, and the object managed by this List has a relation of Child extends Parent
. Then, there is an instance of each List
Generics are not covariant, so you can't:
Map<Key, List<Parent>> map1;
Map<Key, List<Child>> map2;
list1 = list2; //Compile error here
Therefore, we use wildcards. However, the following is also NG
Map<Key, List<? extends Parent>> map1;
Map<Key, List<Child>> map2;
list1 = list2; //Compile error here
this is,
List<? extends Parent> list1;
List<Child> list2;
list1 = list2;
I could do it, but I thought it was strange. And the following is the correct answer
Map<Key, ? extends List<? extends Parent>> map1;
Map<Key, List<Child>> map2;
map1 = map2;
As you can see, I had to use the wildcard twice. I used this to define a method and execute it.
List<Integer> ilist = new ArrayList<Integer>();
ilist.add(1);
ilist.add(2);
ilist.add(3);
Map<String, List<Integer>> imap = new HashMap<String, List<Integer>>();
imap.put("1", ilist);
doit(imap);
public void doit(Map<String, ? extends List<? extends Number>> inmap) {
for (String key : inmap.keySet()) {
System.out.println("key = " + key);
List<? extends Number> list = inmap.get(key);
for (Number n : list) {
System.out.println(n);
}
}
}
bonus:
A method that returns a Map with List <Parent>
as the value from List <Child>
Part 1
public <V, K extends T, T> Map<V, List<? extends T>> convert(Map<V, List<K>> srcMap) {
Map<V, List<? extends T>> dstMap = new HashMap<V, List<? extends T>>();
for (V key : srcMap.keySet()) {
dstMap.put(key, srcMap.get(key));
}
return dstMap;
}
Part 2
public <V, K extends T, T> Map<V, List<T>> toUpper(Map<V, List<K>> srcMap) {
Map<V, List<T>> dstMap = new HashMap<V, List<T>>();
for (V key : srcMap.keySet()) {
List<T> tlist = new ArrayList<T>();
for (K val : srcMap.get(key)) {
tlist.add(val);
}
dstMap.put(key, tlist);
}
return dstMap;
}
Probably "No. 2" is better. The reason is that the return type is Map <V, List <T >>
. According to Effective Java, it is not good to make this method aware of wildcards on the execution side (e.g., List <? Extends T>
) as in "Part 1" (probably ...).
Please point out any mistakes.
Recommended Posts