1

In Java, what is the difference between:

public void foo(List lst);

and

public void foo(List<?> lst);

2 Answers2

0

The first version is a 'List of any type'. This is not generic, not safe and not recommended.

The second version is a 'List of unknown type'. This means you will get objects of the most general type Object, and won't be able to add anything else than null. Since these are the only type safe operations when nothing is known about the type.

You might think the version version is more succinct, and it is. However duck typed languages tend to be more succinct, but that doesn't make them the right choice. Using the raw List is only possible due to backwards compatibility, and you will get a compiler warning.

For more fun, consider the following types, and how they differ from your two:

  • foo(List<Object> list)
  • foo(List<? extends Object> list)
  • foo(List<? super Object> list)
  • foo(List<? super Iterable<? extends Object>> list)
Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
-1

AFAIK:

Just using List lst is a raw type, therefore not typesafe. It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is bad. Not recommended to use. Additional information on raw types : What is a raw type and why shouldn't we use it?

In the case of List: is an unbounded wildcard.

Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • I accepted this because the answer is inside one of the answers that you linked to. Thank you, as everyone else has been horribly inept at providing any semblance of a correct response. – Andruw Holmes Nov 07 '14 at 17:52