Why is this use of Java Generics not compiled?

Throughout life, I cannot understand why the compiler will not allow me to do the following ...

import java.util.HashMap;
import java.util.Map;

public class TestMap {
   private final Map<Integer, ? extends Number> map = new HashMap<Integer, Number>();

   public void put(Integer key, Long item) {
      this.map.put(key, item);
   }
}

Why this.map.put(key, item)does a string cause a compilation error?

I know that I can change the declaration of the map to use Number, and not ? extends Numberto make it work, but it seems to me that what I am doing is completely legal, and I would prefer not to allow Number objects on the map. I am using Java 1.6.0_13.

+3
source share
3 answers

, . , , a List<Float> , List<? extends Number>, Long. , , , .

+10

.

,

Map<Integer, ? extends Number> map

- , , ? extends Number Long, .

:

   Map<Integer, ? extends Number> map = new HashMap<Integer, Integer>();

   public void put(Integer key, Long item) {
      this.map.put(key, item);
   }

Integer != Long, ? extends Number.

+7

.

0

Source: https://habr.com/ru/post/1723788/


All Articles