I would like to know the use of ? in java generics. By studying placeholder T and the wildcard ? , I wondered about ?, gone through several websites/pages and books but failed to understand it. So I created the below class to study the differences.
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
}
}
Here in one case , There might be several scenarios missing from my class so what I have written is incomplete, in this case can anyone please help me to realize more scenarios. Or I found ? as redundant from , except it provides features like , use of super keyword and lesser characters in a method signature along with return type.
EDIT: Basically my question is to know the reasons behind, the purpose of introducing ? wildcard where a generic type can replace it everywhere. It is not the question of how to use ? or T types. Ofcourse, knowing its usage will provide someanswers. For example , the things I have deduced:
Are there any more?
?
means: the type is unspecified. Meaning: if there is no other reason in your code that requires that you have a "named" type parameter; you can/should use ?
to express exactly that.
And actually, I asked that some time back, so you might find the answers here helpful: Java generics: wildcard<?> vs type parameter<E>?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With