定义
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));
天蓬老师2017-04-18 10:50:45
<?> can be written arbitrarily without restrictions,
<T> requires that the places where T appears are of the same generic type
伊谢尔伦2017-04-18 10:50:45
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
private static <T> T fun1(List<T> list) {
}
or
public interface Main<T> {
public void fun(T t);
}
//然后
public class MainImpl<String> {
@override
public void fun(String str) {
}
}
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.
PHP中文网2017-04-18 10:50:45
? 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? .