Home > Enterprise >  Not able to create a map with generic class as key and a list of generic type objects as value
Not able to create a map with generic class as key and a list of generic type objects as value

Time:08-17

I am trying to construct a hashmap of class (key) to the list of tasks (value) for that particular class. Here's my code:

public class StaticTaskListProvider<TEntity extends ScannableEntity> {

    private final Class<TEntity> entityType;
    private static Map<Class<? extends ScannableEntity>, List<Task<? extends ScannableEntity>>> entityToTaskListMap;

    public StaticTaskListProvider(Class<TEntity> entityType) {
        this.entityType = entityType;
        initializeMap();
    }

    private void initializeMap() {
        entityToTaskListMap = new HashMap<>();
        entityToTaskListMap.put(EntityA.class, entityATaskList());
                                               ^^^^^^^^^^^^^^^^^^
    }

    private List<Task<EntityA>> entityATaskList() {
        List<Task<EntityA>> entityATaskList = new ArrayList<>();
        entityATaskList.add(new NewTask());
        return entityATaskList;
    }

But I am getting the following error while trying to add the List<Task<EntityA> to the map even though the EntityA extends ScannableEntity.

 error: incompatible types: List<Task<EntityA>> cannot be converted to List<Task<? extends ScannableEntity>>
        entityToTaskListMap.put(EntityA.class, entityATaskList());
                                                             ^

CodePudding user response:

I hope this helps you:

private List<Task<? extends ScannableEntity>> entityATaskList() {
    List<Task<? extends ScannableEntity>> entityATaskList = new ArrayList<>();
    entityATaskList.add(new NewTask());
    return entityATaskList;
}

CodePudding user response:

quote from oracle documentation

Given the following two regular (non-generic) classes:

class A { /* ... */ } 
class B extends A { /* ... */ }

It would be reasonable to write the following code:

B b = new B(); 
A a = b;

This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A.
This rule does not apply to generic types:

List<B> lb = new ArrayList<>(); 
List<A> la = lb;   // compile-time error

In your example, Task<EntityA>(as B) is a subtype of Task<? extends ScannableEntity>(as A),but List<Task<EntityA>>(as List<B>) is not a subtype of List<Task<? extends ScannableEnity>>(as List<A>).

  • Related