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) {}
method 2
public static <T> double sumOfList(List<T> list) {}
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) {}
method 2
public static <T> double sumOfList(List<T> list) {}
Inside the method you can use T
in second case .
You cannot in first case.
Consider this example
private static <T> void printList(List<T> list) {
for (T t: list) {
System.out.println(t);
}
}
In this case, there is no difference. T
is only used in one place in the parameter, so it does not enforce a relationship between types in two places.
In other cases, e.g. if T
is in the return type:
public <T> List<T> newList();
or if T
is used in multiple places:
public <T> T foo(T x);
public <T> void bar(List<T> list, T x);
or if T
is recursively bounded:
public <T extends Comparable<? super T>> void sort(T[]);
you cannot do it with a wildcard.
In second method you can use like that:
T t;
However you can't in first method. I think that it's the difference. I hope it will help you.