我试图在接收器的类型和
Java中的方法的参数类型中使用通配符的组合.上下文是定义容器的上下文.现在,类型Container不应该允许任何插入,因为此类型不指定包含的对象的类型.但是,如果底层数据结构允许,则应该有一种方法来搜索类型为T的对象,或者任何其他类型的对象.
这是一个演示此问题的代码段.关于如何在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.
}
}
}
最佳答案 错误消息正在告诉您究竟是什么问题.你的find方法使用泛型R extends T,在这种情况下T是?,所以编译器无法检查你提供的R(一个Item)来检查它是否扩展了“capture#6-of?”.