问题描述
我主要是C#开发人员,我正在向我的朋友教授数据结构,他们在他们的大学中使用Java,我在Java中看到了这样一个表达式:
<$ p $ (对象e:c){
System.out.println(e); $ {
for $ {code>
}
}
我还没有在C#中看到过这样的事情我想知道Java中的 Collection< T> 和 Collection < / code>有什么区别?
void printCollection(Collection< T> c){
for(Object e:c){
的System.out.println(E);
}
}
我认为它可以用上面的方式编写太。文档中的人比较了 Collection 和 Collection
$ b
示例摘自
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> {
列表< Set< T>> sets = new ArrayList<>();
public C(){
sets.add(new HashSet< String>()); //不会编译
sets.add(new HashSet< Integer>()); //不会编译
}
}
I am mainly a C# developer and I was teaching Data Structures to my friend and they use Java in their University and I saw such an expression in Java:
void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } }
I haven't seen such a thing in C# so I wonder what's the difference between Collection<T> and Collection<?> in Java?
void printCollection(Collection<T> c) { for (Object e : c) { System.out.println(e); } }
I think it could have been written in the way above too. The guy in the documentation was comparing Collection<Object> and Collection<T> though.
Examples are taken from http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
Collection<?> is a collection of unknown type parameter.
As far as the caller is concerned, there is no difference between
void printCollection(Collection<?> c) { ... }
and
<T> void printCollection(Collection<T> c) { ... }
However, the latter allows the implementation to refer to the collection's type parameter and is therefore often preferred.
The former syntax exists because it is not always possible to introduce a type parameter at the proper scope. For instance, consider:
List<Set<?>> sets = new ArrayList<>(); sets.add(new HashSet<String>()); sets.add(new HashSet<Integer>());
If I were to replace ? by some type parameter T, all sets in sets would be restricted to the same component type, i.e. I can no longer put sets having different element types into the same list, as evidenced by the following attempt:
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 } }
这篇关于Collection<>的区别是什么?和Collection< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!