I get errors with the following code (as described below the snippet):
public class MyClass {
private Map<String, Subclass1> mapToSubclass1;
private Map<String, Subclass2> mapToSubclass2;
public void update(
final boolean updatesAreSubclass1,
final List<? extends Superclass> updates) {
Map<String, Superclass> mapToUpdate;
if (updatesAreSubclass1) {
mapToUpdate = mapToSubclass1;
} else {
mapToUpdate = mapToSubclass2;
}
updates.stream().forEach((entity) -> {
mapToUpdate.put(entity.getId(), entity);
});
}
}
where Subclass1 and Subclass2 extend Superclass, and Superclass provides public String getId();.
As written, I get errors when attempting to define mapToUpdate - Incompatible types. Required: Map<String, foo.bar.Superclass>, Found: Map<String, foo.bar.Subclass1> (or Subclass 2, in the else-clause).
If I change mapToUpdate to a Map<String, ? extends Superclass>, I get an error when attempting to put - Wrong 2nd argument type. Found: 'foo.bar.Superclass', required '? extends foo.bar.Superclass'
I think this is to do with the notion of covariance, but I'm not sure how to resolve the problem. A couple of solutions I came up with, neither satisfactory:
- Should I need two
updatemethods, one for each Subclass (This gets messy quickly if there are more than two)? - Should I move the
putinside theif (updatesAreSubclass1)clause, and castupdatesto the appropriateList<Subclass>?