0

I'm currently learning Java generics, and while going through the Oracle's tutorial in Wildcard capture and helper methods it suddenly hit me: what is the benefit of:

void someMethod(List<?> list) { // .. }

over:

<T> void someMethod(List<T> list) { // .. }

?

The reason I ask is that the link provided above presents a certain compilation error that occurs while using the first form (using wildcards), which is solved by using a helper method of the second form. So the question arises - why use the first form in the first place?

YoavKlein
  • 2,005
  • 9
  • 38
  • You need to use the second form if you are trying to put something back into the `list` - in the first form, even if it is something you took out of the list (e.g. `list.add(list.get(0));`), the compiler doesn't recognize it as being of the correct type. The second form allows the compiler to know that the thing is of type `T`; because you can add a `T` to a `List`, the compiler allows this. – Andy Turner Jul 31 '23 at 10:30
  • If you don't need to add anything to `list` (more generally, invoke a method which accepts a `T` or a type referencing `T` as a parameter), it's just unnecessary to have it there. – Andy Turner Jul 31 '23 at 10:32

1 Answers1

-2

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).

The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a super type.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197