In Java, what is the difference between:
public void foo(List lst);
and
public void foo(List<?> lst);
In Java, what is the difference between:
public void foo(List lst);
and
public void foo(List<?> lst);
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)
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.