I have a problem with generic classes in java.
I have this class:
public abstract class MyMotherClass<C extends AbstractItem>
{
private C item;
public void setItem(C item)
{
this.item = item;
}
public C getItem()
{
return item;
}
}
The implementation of this class may be:
public class MyChildClass extends MyMotherClass<ConcreteItem>
{
}
ConcreteItem is just a class that extends AbstractItem (which is abstract).
so MyChildClass has ConcreteItem and I can use:
MyChildClass child = new MyChildClass();
child.setItem(new ConcreteItem());
// automatic cast due to generic class
ConcreteItem item = child.getItem();
Well, at the moment, everything is in order. Here is the problem:
Now I want to extract an instance of MyMotherClass from the collection and set its element (which type is unknown):
Map<String, MyMotherClass> myCollection = new HashMap<String, MyMotherClass>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
...
MyMotherClass child = myCollection.get("key");
child.setItem(myItems.get("key2"));
If I like it, it works. BUT I have a warning because MyMotherClass is a generic type and I am not using a generic type. But I don't know what type of my extracted child is, so I want to use a wildcard:
Map<String, MyMotherClass<?>> myCollection = new HashMap<String, MyMotherClass<?>>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
...
MyMotherClass<?> child = myCollection.get("key");
child.setItem(myItems.get("key2"));
: , :
setItem ( # 1-of?) MyMotherClass (AbstractItem)
, :
Map<String, MyMotherClass<? extends AbstractItem>> myCollection = new HashMap<String, MyMotherClass<? extends AbstractItem>>();
Map<String, AbstractItem> myItems = new HashMap<String, AbstractItem>();
...
MyMotherClass<? extends AbstractItem> child = myCollection.get("key");
child.setItem(myItems.get("key2"));
?
, ;)