Java – generic methods do not recognize types correctly
I have a class whose members are defined as:
Map<Class<? extends Model>,List<? extends Model>> mockStore;
In this class, I have a method:
protected <T extends Model> void insertMockStore(T obj) { mockStore.get(obj.getClass()).add(obj); }
However, this method will produce compilation errors:
Method add (capture #8-of? Extensions model) in type list is not applicable to parameter (T)
I don't understand this error because t is defined as an extended model. Why does it say t doesn't apply?
Solution
Your member declaration indicates that the value of mockstore will be a list containing unspecified subclasses * of model
The insertmockstore method is similar, but there is no guarantee that the subclass of the model passed to insertmockstore is the same as the list
What you should do is announce the mockstore like this:
Map<Class<? extends Model>,List<Model>> mockStore;
An easy rule of thumb to remember is the "PECS rule": producer expansion, consumer super This means that if your member has a collection with a type parameter foo, all generator type methods (those inserted into your collection) will need t extensions Foo and all consumer type methods (those that return values from the collection) should have t super foo
*As with generics, we include the class itself in the "subclass"