定义
public static void printList(List<?> list) {
for (Object elem : list){
System.out.println(elem + " ");
}
}
public static <T> void printList2(List<T> list) {
for (T elem : list){
System.out.println(elem + " ");
}
}
使用
MyList.printList(Arrays.asList(1, 2, 3));
MyList.printList2(Arrays.asList(1, 2, 3));
<?> can be written arbitrarily without restrictions,
<T> requires that the places where T appears are of the same generic type
The effect is the same, it does not mean that <T> requires that the places where T appears are of the same type. In fact, the above two methods are compiled into bytecode. List<T> and List<?> are both List<Object> at the bottom level.
But the second usage does not play any role in actual development. Why, unless the generic is the type that declares the return value, or it is declared at the class level. For example
or
This is what worked.
Otherwise, use it like this
public static <T> void fun1(List<T> list)
What is the role of generics here? I really don't see what effect it has. It should be said that there is no need to use it this way.
? Both T and T represent uncertain types, but using T can perform object operations, such as return <T>t; In this case, should T be used instead? .
List<?>
是List<T>
的超类,能使用List<?>
的地方都可以使用List<T>