我有一个包含以下构造函数的类:
public UniqueField(Collection<Object> items) {
this.items=items;
}
Collection<Object>
背后的想法是我可以使用Collection<OtherType>
。
做的时候:
Collection<OtherType> collection=...
new UniqueField(collection);
我收到无效参数的编译错误。我该如何解决这个问题?
答案 0 :(得分:4)
你必须改用
public UniqueField(Collection<? extends Object> items) {
this.items=items;
}
或?因为它等于“?extends Object”
public UniqueField(Collection<?> items) {
this.items=items;
}
您可以看到here的原因
答案 1 :(得分:0)
你可以使用:
public UniqueField(Collection<?> items) {
this.items=items;
}
或:
public UniqueField(Collection<? super OtherType> items) {
this.items=items;
}
或简单地说:
public UniqueField(Collection<OtherType> items) {
this.items=items;
}