在java泛型编程中,没有通配符的参数类型的对象类是上界还是下界?
在回答问题时Creating generic array in Java via unchecked type-cast,newacct说
(The lower bound of Bar is Object in this question. In a case where the lower bound of Bar is something else, replace all occurrences of Object in this discussion with whatever that bound is.)
以下是newacct的代码:
class Foo<Bar> {
Bar[] bars = (Bar[])new Object[5];
public Bar get(int i) {
return bars[i];
}
public void set(int i, Bar x) {
bars[i] = x;
}
public Bar[] getArray() {
return bars;
}
}
我想知道Object
是Bar
的上界还是下界。我认为Foo<Bar>
是Foo<Bar extends Object>
的缩写,所以Object应该是Bar
的上界,我错了吗
# 1 楼答案
给定类型变量声明} is assumed ,所以在本例中,
<T extends TypeName>
,TypeName
是T
的上界。从技术上讲,我认为这只是界,因为上/下的区别是only made for wildcards。另外,if no bound is specified, then ^{Object
是Bar
的界是正确的我认为newacct在写答案时只是说错了,意思是说“上限”而不是“下限”
编辑:同样,当谈论参考Q&;中的特定构造时;A、 有必要指出the erasure of a type variable is the erasure of its left-most bound,这是用绑定中使用的类型替换用于创建数组的元素类型的重要性。例如,给定一个复杂类型变量声明
<T extends Comparable<T> & Serializable>
,对T
的擦除将是Comparable
,因此可以使用Comparable[]
或Comparable<?>[]
# 2 楼答案
您也可以在泛型中定义下限,如下所示
}
所以,您可以使用扩展Bar的任何类创建一个Foo对象
不,不能使用对象类型实例,下限为Bar,上限为扩展Bar类的任何类