我想了解在Java泛型中?的用法。通过学习占位符T和通配符?,我对?产生了疑问,查阅了几个网站/页面和书籍,但未能理解它。因此,我创建了下面的类来研究它们之间的区别。
import java.util.List;
public class Generics2 {
public <T> void method1(List<T> list){
System.out.println(list);
}
public <T extends Number> void method2(List<T> list){
System.out.println(list);
}
/*public <T super Integer> void method3(List<T> list){
}*///super does not work.
public void method4(List<?> list){
System.out.println(list);
}
public void method5(List<? extends Number> list){
System.out.println(list);
}
public void method6(List<? super Integer> list){
System.out.println(list);
}
public <T> void copy1(List<T> list1, List<T> list2){
//copy elements from list1 to list2
}//It does not span well with copy of one type of elements from list1 to other type elements in list2, where the list elements
//between the two are not same but are related through inheritance.
public <T1,T2> void copy2(List<T1> list1,List<T2> list2){
//copy elements from list1 to list2, right now we do not bother about the exceptions or errors that might generate.
}//Our intention here is not to copy elements with relation between T1 and T2. We intend to explore the differences on T and ?
public void copy3(List<?> list1,List<?> list2){
//copy elements from list1 to list2, right now we do not bother about the exceptions or errors that might generate.
}//Our intention here is not to copy elements with relation between T1 and T2. We intend to explore the differences on T
public <T1 extends Object, T2 extends Object> void copy4(List<T1> list1, List<T2> list2){
//copy elements from list1 to list2
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
在某些情况下,我的类可能会缺少几个场景,因此我写的不完整,在这种情况下,是否有人可以帮助我实现更多场景。或者我发现?在某些方面是多余的,除了提供像使用super关键字和方法签名中的返回类型较少的功能之外。
编辑:基本上我的问题是要知道引入通配符?的原因,其中一个泛型类型可以替代它。这不是如何使用?或T类型的问题。当然,了解其用途将提供一些答案。 例如,我得出的结论:
- 在某些地方,?使代码更易读,但编码不太容易。 - 它有时会减少代码膨胀。 - 我们可以使用超类,而T类型无法做到这一点。 - 限制向列表添加新的随机元素。在某些情况下,对于T类型,强制转换(没有classcastexception)是有效的。
还有其他吗?