'Java incompatible type <A> cannot be converted to wildcard parameter <? extends B> inside HashMap<>

Recently I have come across the following error during compilation:

error: incompatible types: HashMap<Integer, HashMap<Object, Consumer<A>>> cannot be converted
to HashMap<Integer, HashMap<Object, Consumer<? extends B>>>

In this code, class A is a direct subclass of B.

This error occurred in the following snippet:

HashMap<Integer, HashMap<Object, Consumer<A>>> item = new HashMap<>();
HashSet<HashMap<Integer, HashMap<Object, Consumer<? extends B>>>> set = new HashSet();
set.add(item);

In attempting to resolve the error I have already tried removing the ? extends bit from the HashMap inside of the HashSet, but the compiler kept throwing the error.



Solution 1:[1]

Consumer<A> and Consumer<? extends B> are totally different , in fact Consumer<? extends B> can be Consumer<C> where C is another class who extends B.

The same with Consumer<A> and Consumer<B> they are not the same thing, an instance of B class is not an instance of A class, so deleting the ? extends still give you a compile time error.

import java.util.ArrayList;
import java.util.List;

public class Test {
    static class Lion extends Animal {
    }
    static class Animal {
    }
    public static void main(String[] args) {
        List<? extends Animal> animals = new ArrayList<Animal>();
        animals .add(new Lion()); // DOES NOT COMPILE 

        // at compile time , our List(reference) may be a List of Animal or List of Lion , not a List of both of them
        
        // using ? extends Animal to refer the ArrayList instance 
        // we cannot add a Lion to an ArrayList of Animal

        animals .add(new Animal()); // DOES NOT COMPILE

        // the same using the ? extends Animal as reference 
       // we cannot add an animal to an ArrayList of Lion
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1