Winston Liek wrote:For example, if I change:...
But this is precisely what you
don't do. The whole point of generics is that it can be used with all sorts of types, so there's no point in changing them.
public static <K, V> List<V> getListFromMapValues(Map<K, ? extends V> map)
says:
"The method takes a Map with a key type of K and returns a List of type V, either of which can be ANY
Java class.
Since V might have subclasses, and the Map's
values will be used to populate the List, the value type of the Map must be either V itself, OR a type that
extends V."
There is no idea of "changing" method declarations, what you do is
call the method according to the rules it specifies.
So if you have two Maps:
Map<String, Number> map1 = new HashMap<String, Number>(); and
Map<String, Integer> map2 = new HashMap<String, Integer>();
the following calls:
List<Number> list1 = getListFromMapValues(map1);,
List<Number> list2 = getListFromMapValues(map2); and
List<Integer> list3 = getListFromMapValues(map2);
are legal, but:
List<Integer> list4 = getListFromMapValues(map1);
is not.
This is because
map1 is a
Map<String, Number>, but
list4 is a
List<Integer>, which means that for that call,
V == Integer. But the
map's value type is
Number, which is NOT a subclass of
Integer.
Hope it helps. Generics can be quite tough to get your head around to begin with and, from time to time, I
still have to go back to the tutorials.
Winston