例如:
public String add(Set<?> t){
...;
}
public <T> String add(Set<T> t){
...;
}
第一个使用通配符泛型;第二种是泛型方法的范式。
有什么不同?
在什么情况下我们需要通配符泛型,而不是普通形式的泛型?
这是需要通配符的情况。该方法需要一个List<List<?>>
,这是一个列表的列表。该方法可以向其中添加不同组件类型的列表:
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>()); // does not compile
t.add(new ArrayList<Integer>()); // does not compile
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)