我主要是一名 C# 开发人员,我正在给我的 friend 教授数据结构,他们在大学里使用 Java,我在 Java 中看到了这样的表达:
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
我在 C# 中没有见过这样的东西,所以我想知道 Java 中的 Collection<T>
和 Collection<?>
有什么区别?
void printCollection(Collection<T> c) {
for (Object e : c) {
System.out.println(e);
}
}
我认为它也可以按照上面的方式编写。文档中的那个人正在比较 Collection<Object>
和 Collection<T>
。
示例取自http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
最佳答案
Collection<?>
是未知类型参数的集合。
就调用者而言,没有区别
void printCollection(Collection<?> c) { ... }
和
<T> void printCollection(Collection<T> c) { ... }
但是,后者允许实现引用集合的类型参数,因此通常是首选。
前一种语法之所以存在,是因为并不总是可以在适当的范围内引入类型参数。例如,考虑:
List<Set<?>> sets = new ArrayList<>();
sets.add(new HashSet<String>());
sets.add(new HashSet<Integer>());
如果我要替换 ?
通过某些类型参数 T
, 所有集合在 sets
将被限制为相同的组件类型,即我不能再将具有不同元素类型的集合放入同一个列表中,以下尝试证明了这一点:
class C<T extends String> {
List<Set<T>> sets = new ArrayList<>();
public C() {
sets.add(new HashSet<String>()); // does not compile
sets.add(new HashSet<Integer>()); // does not compile
}
}
关于java - Collection<?> 和 Collection<T> 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10777701/