Let's say we have a program that contains such classes:
public interface AbstractItem {
}
public SharpItem implements AbstractItem {
}
public BluntItem implements AbstractItem {
}
public interface AbstractToolbox {
public List<AbstractItem> getItems();
}
public ExpensiveToolbox implements AbstractToolbox {
private List<SharpItem> items = new ArrayList()<SharpItems>;
public List<SharpItem> getItems() { return this.items; }
}
public CheapTooblox implements AbstractToolbox {
private List<BluntItem> items = new ArrayList()<BluntItem>;
public List<BluntItem> getItems() { return this.items; }
}
Easy, right? Well let's say, now we want to make such a method (in some random class):
public void doImportantStuff(AbstractToolbox toolbox) {
List<AbstractToolbox> items = toolbox.getItems();
}
Now the problem is that in Java collections with generics are not covariant (I hope that this term I am looking for), and I can not assign ArrayList<ExpensiveToolbox>for List<AbstractToolbox>. The only solution I see here is to duplicate the code and make a version for each type, but this is obviously a suck (what if we had more classes that implement AbstractToolbox with different lists?). Obviously, the second solution would be to give up generics and make a regular list, but is this a good practice?
Are there any design patterns / methods to solve such problems?
@Edit: ok, . , , AbstractToolbox, , AbstractItem, , AbstractToolbox - ( , AbstractItem, ).