4

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) {}
Randyka Yudhistira
  • 3,612
  • 1
  • 26
  • 41
user2761885
  • 327
  • 1
  • 7
  • 13

3 Answers3

9

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);
}

}

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 3
    Also, in the first case you can pass in a list of any type of objects, in the second you are limited to a List of T instances. Another interesting version would take a `List extends T>` – John B Sep 13 '13 at 13:24
  • 1
    List of T doesn't mean list of any type of object? Doesn't T mean any type of object? – user2761885 Sep 13 '13 at 13:40
  • @SJuan76 Yes.Thankyou so much.I linked a wrong one.Edited my post with another example,Which clarifies OP's doubt also. – Suresh Atta Sep 13 '13 at 13:50
  • @user2761885 `Doesn't T mean any type of object` yes.your understanding is correct. – Suresh Atta Sep 13 '13 at 13:53
  • 1
    But in this case, you don't need to use `T` in the method. You can just use `Object`. `private static void printList(List> list) { for (Object t: list) { System.out.println(t); }` So this example doesn't show anything. – newacct Sep 13 '13 at 20:33
  • @JohnB: You can pass in the same things to both methods. A "list of any type of objects" is still a list of "some kind" of object. That kind is `T`. – newacct Sep 13 '13 at 20:35
  • @newacct in this case yes, but as a study of wildcards I thought it was a good point to bring up since these two would be different: ` void method(T value, List list)` vs ` void method(T value, List extends T> list)` – John B Sep 13 '13 at 20:44
2

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.

newacct
  • 119,665
  • 29
  • 163
  • 224
0

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.

Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
Louis
  • 9
  • 2
  • So, why would you need to use `T t;`? – newacct Sep 13 '13 at 20:40
  • If you can use T in the second method, but cannot in the first method why would you ever select the first method? It's a restricted version of the second method. Why would you want these restrictions? – barrypicker Jan 16 '20 at 00:12