通配符泛型真的需要吗? [英] Are wildcard generics really needed?

查看:134
本文介绍了通配符泛型真的需要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

  public String add(Set <?> t){
...;
}



public< T> String add(Set< T> t){
...;
}

第一个使用通配符泛型;第二种是通用方法的正常形式。
有什么区别?



在什么情况下我们需要通配符泛型,而不是普通的泛型?

解决方案

这是一个需要通配符的情况。该方法采用 List< List<>>< / code>这是列表的列表。该方法可以添加不同组件类型的列表到其中:

  public void foo(List< List<>> t ){
t.add(new ArrayList< String>());
t.add(new ArrayList< Integer>());
}

不能使用不含通配符的泛型类型参数。例如,以下内容不起作用:

  public< T> void foo(List< List< T> t){
t.add(new ArrayList< String>()); //不会编译
t.add(new ArrayList< Integer>()); //不会编译
}


for example:

    public String add(Set<?> t){
    ...;
    }



    public <T> String add(Set<T> t){
    ...;
    }

The first uses wildcard generics; the second is the normal form of a generic method. What's the difference?

In what situation do we need wildcard generics, not the normal form of generics?

解决方案

Here is a situation where wildcards are required. This method takes a List<List<?>>, which is a list of lists. The method can add lists of different component types into it:

public void foo(List<List<?>> t) {
    t.add(new ArrayList<String>());
    t.add(new ArrayList<Integer>());
}

You cannot do this using generic type parameters without wildcards. For example, the following does not work:

public <T> void foo(List<List<T>> t) {
    t.add(new ArrayList<String>()); // does not compile
    t.add(new ArrayList<Integer>()); // does not compile
}

这篇关于通配符泛型真的需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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