0

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.

charmander
  • 33
  • 4
  • 1
    `A is a direct subclass of B.` This looks like a direct application of "generics aren't covariant." https://stackoverflow.com/questions/8481301/covariance-invariance-and-contravariance-explained-in-plain-english – markspace Apr 05 '22 at 23:26

1 Answers1

0

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
    }
}
Oussama ZAGHDOUD
  • 1,767
  • 5
  • 15