集合<?>和集合< T> [英] What is the difference betwen Collection<?> and Collection<T>

查看:155
本文介绍了集合<?>和集合< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要是一个C#开发人员,我正在教我的数据结构给我的朋友,他们在他们的大学使用Java,我在Java看到这样的表达式:

  void printCollection(Collection<?> c){
for(Object e:c){
System.out.println(e)
}
}



我没有在C#中看到这样的事情我不知道在Java中集合< T> 集合<?> 有什么区别?

  void printCollection(Collection< T> c){
for(Object e:c){
System.out.println(e);
}
}

我认为它可能是以上面的方式写的太。文档中的人正在比较 Collection< Object> Collection< T>
$ b

示例取自 http://docs.oracle.com /javase/tutorial/extra/generics/wildcards.html

解决方案

集合< ;? > 是未知类型参数的集合。



对于调用者,

  void printCollection(Collection<?> c){...} 

 < T& void printCollection(Collection< T> c){...} 



前一种语法存在,因为并不总是可能在适当的范围内引入一个类型参数。例如,考虑:

 列表< Set<?>> sets = new ArrayList<>(); 
sets.add(new HashSet< String>());
sets.add(new HashSet< Integer>());

如果我替换类型参数 T 集中的所有集合将被限制为相同的组件类型,即我不能再将集合具有不同的元素类型到同一列表中,如以下尝试所证明的:

  class C< T extends String> {
List< 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
    }
}

这篇关于集合&lt;?&gt;和集合&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆