java unbound wildcard <?> vs <T>

use*_*885 4 java generics

I am confusing that if the following method are same? Are there any subtle differences?

Your advice are very appreciated.

method 1

public static double sumOfList(List<?> list) {}
Run Code Online (Sandbox Code Playgroud)

method 2

public static <T> double sumOfList(List<T> list) {}
Run Code Online (Sandbox Code Playgroud)

Sur*_*tta 8

在方法内部,您可以T 在第二种情况下使用.

你不能在第一种情况下.

考虑这个例子

private static <T> void printList(List<T> list) {
for (T t: list) {
    System.out.println(t);
}
Run Code Online (Sandbox Code Playgroud)

}

  • 此外,在第一种情况下,您可以传入任何类型的对象的列表,在第二种情况下,您仅限于T实例列表.另一个有趣的版本将采用`List <?扩展T>` (3认同)