1

what is the difference between these 2 method signatures?

  1. public <T> void fromArrayToList(List<?> a) { }

  2. public <T> void fromArrayToList(List<T> a) { }

One is taking a List<T>, and the other is taking a List<?>. I am able to pass a list containing objects of any type to both these methods without the compiler complaining.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    In the first one (the `` is obsolete), the type is unknown to you. In the second, you know the type and can name it, namely `T`. So the second would allow you to do `T foo = a.get(0)` and then `a.add(foo)`. The first cant do this, since you can not capture the type to put it back in (actually, you can with `var` or by just going raw-types...). – Zabuzard Apr 09 '22 at 19:23
  • In general, you use wildcards if you truly dont care about the type. But use generics if you actually need to be able to name the type. – Zabuzard Apr 09 '22 at 19:24

0 Answers0