<? extends Object>
和<E extends Object>
有什么区别?何时应该使用其中之一?
这是我马上想到的一些不同之处:
Type parameter bounds can specify multiple bounds - T extends A & B
, but with wildcard you cannot specify multiple bounds - ? extends A & B
is invalid.
You can have lower bounds with wildcard - ? super A
is valid, but not with the type parameter - T super A
is not valid.
You cannot use wildcard bounds while creating a generic type. You have to use type parameter bounds.
Inside a method, if you want some relation between the type parameters of arguments passed, then you have to use type parameter bounds. For e.g, you want to pass two parameterized type with same type parameter. You can't do this with wildcard bounds. So the following method declaration will take two list of same type parameter, that extends Number
.
public <T extends Number> void merge(List<T> list1, List<T> list2) {
}
参考资料:
<? extends Object>
是一个有界通配符(扩展自Object
的未知类型),而<E extends Object>
是类型受限的(E
需要一个扩展Object
的参数化类型)。创建泛型类时无法使用有界通配符,只允许使用带类型的参数。
无法在需要向集合中添加项目的Collection
中使用有界通配符,因为它是一个未知类型,集合不知道接收到的是什么类型,因此它不是类型安全的。
无法将有界通配符绑定到多个泛型类型(边界)。
<? extends Object>
和<E extends Object>
都是有界的,它们的上限是Object
。 - KatonaCollection<? extend Object> collection = new ArrayList<? extends Object>();
。现在,添加一个项目。如果您使用Eclipse IDE,您将看到它说,collection.add(null e)
。这就是我的意思。?
是一个通配符无界限制,这就是我在帖子中提到的。 - Buhake Sindi如果您需要在后面引用该类型,请使用E
。如果您不再需要引用该类型,请使用?
。
<E>
声明了一个类型参数。
只有在创建泛型类型或方法时才能使用它。
<? ...>
是类型参数的通配符 值。
只有在创建封闭泛型类型时才能使用它。
E
。 - Sotirios Delimanolis<? extends AClassOrInterface>
来处理集合(set、list、map等)的元素,仅此而已。如果我想要字段(类型为 E 的字段或填充有类型为 E 的元素的集合)的类/接口定义,我会使用<E extends MyClass>
。 - Luiggi Mendoza