Не могу добавить наследника в мапу (Wildcards)
Компилятор ругается на то что передаю наследника класса Animal в Мапу. Cat его наследует, но в Мапу добавить не могу. Компилятор выдает:
The method put(capture#1-of ? extends Animal, Integer) in the type Map<capture#1-of ? extends Animal,Integer> is not applicable for the arguments (Cat, int)
Не понимаю почему это происходит. Помогите.
Cat sebas = new Cat("Себастьян", 10);
Animal cat = new Animal("Кошка", 1);
Map<? extends Animal, Integer> animals = new HashMap<>();
animals.put(sebas, sebas.getAnimalID());
Ответы (2 шт):
Автор решения: Никита Жуков
→ Ссылка
Замените Map<? extends Animal, Integer> animals = new HashMap<>() на Map<Animal, Integer> animals = new HashMap<>()должно сработать.
Автор решения: wigravy
→ Ссылка
Вам нужно заменить extend на super. Подробее с примерами про wildcard можно прочитать тут.
Map<? super Animal, Integer> animals = new HashMap<>();
Animal cat = new Cat();
Cat cat2 = new Cat();
animals.put(cat, 1);
animals.put(new Animal(), 2);
animals.put(cat2, 3);