Hi,
I am trying to use a combination of wildcards in the type of the receiver and in the type of an argument to a method in Java. The context is that of defining a container. Now, the type Container should not admit insertions whatsoever, since this type does not specify the type of the contained objects. However, if the underlying data structure allows it, there should be a way for searching an object of type T, or of any other type that extends T.
Here is a code snippet that demonstrates the problem. Any ideas on how I can achieve this design goal in Java?
public class Main {
public static class Container<T extends Item> {
public void insert(T t) {
System.out.println("Inserting " + t);
}
public <R extends T> int find(R r) {
return r.hashCode();
}
}
public static class Item {
// Nothing here
}
public static class ExtendedItem extends Item {
// And nothing here...
}
public static class Client {
public static void main(String[] args) {
useContainerOfItem();
useContainerWildCardOfItem(new Container<Item>());
Container<? extends Item> c;
c = new Container<Item>(); // OK. type of c, is a super type of Container<Item>
c = new Container<ExtendedItem>(); // OK. type of c, is a super type of Container<ExtendedItem>
useContainerWildCardOfItem(c);
}
private static void useContainerOfItem() {
Container<Item> c = new Container<Item>();
c.insert(new Item()); // OK. We can insert items
c.insert(new ExtendedItem()); // OK. We can insert items
c.find(new Item()); // OK. We can find items in here.
c.find(new ExtendedItem()); // OK. We can also find derived items.
}
private static void useContainerWildCardOfItem(Container<? extends Item> c) {
c.insert(new Item()); // Error: expected. We should not be able to insert items.
c.insert(new ExtendedItem()); // Error: expected. We should not be able to insert anything!
c.find(new Item()); // Error. Why??? We should be able to find items in here.
c.find(new ExtendedItem()); // Error. Why??? We should be able to find items in here.
}
}
}