请考虑以下内容:
public interface Sendable<T> { T details() }
public interface Receiver<T> { void receive(T details) }
我想从任何类型的Sendable到相同类型的Receiver进行映射。它们必须是相同的类型,因为有时我想打电话给
receiver.receive(sendable.details());
,否则编译器将拒绝它。我计划发送许多类型。我可以做类似的事情:
public class Foo {
Map<Sendable<Integer>, Receiver<Integer>> intmap;
Map<Sendable<String>, Receiver<String>> stringmap;
...
//put a map for each type
}
,但是每次我想发送一些新类型时,我都必须更新此类。我想做类似的事情
public class Foo {
Map<Sendable<?>, Receiver<?>> map;
}
因为我只需要编写一次并永久使用它,但这显然是行不通的,因为?不是一个 ?。那么,如何为任何T绘制从T到T的地图?
无需强制转换,可以克服静态键入的问题。