Why does this method work with wildcards?

I came across this question:

We are provided with a map interface:

interface MyMap<K,V>{
  public void put (K key, V value);
  public V get (K key);
  public boolean containsKey (K key);
}

We want to implement a method addToMyMapwhose signature (we need to fill in the missing parts (points):

void addToMyMap(MYMap<....> m, List<....> keys, .... newValue)

The method will check the list of keys, and for each key, if it does not exist on the map, it will add it to the value of newValue.

The implementation provided as an answer was as follows:

 public static <K,V> void addToMyMap (MyMap <? super K, ? super V> m, List<? extends K> keys, V newValue) 
 {
   for (K key: keys)
   {
      if (!m.containsKey(key))
      {
         m.put(key,newValue);
      }
   } 
}

I'm not quite sure why this implementation is correct. How does a method containsKeywork if it gets a subclass of K? Doesn't that look like a search Applein List<Fruit>? How would you even go over this list?

The same applies to the method put: how can it iterate over a map with many different types?

This may be related to the implementation of the Map.

, , , , K V, , Ks.

:

MyMap <Number, Number> m = new MyMapImpl<Number,Number>();
m.put(new Integer (1) , new Float(7.2));
m.put (new Float(3.1), new Double(9.99));

List<Integer> lst = new List<Integer>();
lst.add(1); lst.add(2); lst.add(3);
Float f = new Float (55.5);
Util.addToMyMap (m,lst,f);

, float integer, , float ( put containsKey)?

.

+4
1

The Get and Put Principle: extends, , super, , .

, float integer, , float ( put containsKey)?

? super K , Map , - K. , - .

, List<Integer> , List<? super Integer>, Integer, , Integer.


MyMap <Number, Number> m Number, - Integer, Float. Integer Float. Double . Number. .

, :

+4

All Articles