我试图理解为什么我们需要通配符——Java 泛型中的问号,为什么我们不能只使用普通的单个字符 T 或 E 等作为类型?看下面的例子:
public class App {
public static void main(String[] args) {
App a = new App();
List<String> strList = new ArrayList<String>();
strList.add("Hello");
strList.add("World");
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
a.firstPrint(strList);
a.firstPrint(intList);
a.secondPrint(strList);
a.secondPrint(intList);
}
public <T extends Object> void firstPrint(List<T> theList) {
System.out.println(theList.toString());
}
public void secondPrint(List<? extends Object> theList) {
System.out.println(theList.toString());
}
}
虽然通配符版本更简洁,但结果相同。这是唯一的好处吗?
“?”是否可以充当占位符,您可以在其中传递不同类型的对象。
通常,T 和 ?在泛型中用作占位符。即<?>
或 <T>
.
用例:
<?>:
它可以在开发人员希望允许特定实例的任何类型的对象时使用。
Example: List<?> listOfObject = new ArrayList<>();
Here in this case
listOfObject can accept any kind of object which is extending the
class Object
<T>:
要使用的方法之一是复杂类型的对象 (DTO)。
i.e., Let's say if Class A can have same fields for different instances.
However, there is one field which could be varied with the type of
instances. Meanwhile, it could be the better approach to use Generics with
例子:
public Class A<T> {
private T genericInstance;
private String commonFields;
public T getGenericInstance() {
return this.genericInstance;
}
public String getCommonFields() {
return this.commonFields;
}
public static void main(String args[]) {
A<String> stringInstance = new A<>(); // In this case,
stringInstance.getGenericInstance(); // it will return a String instance as we used T as String.
A<Custom> customObject = new A<>(); // In this case,
customObject.getGenericInstance(); // it will return a custom object instance as we used T as Custom class.
}
}