Considering the two functions:
public static void myFunction(List<?> list);
public static <T> void myFunction(List<T> list);
Please explain why we have included <T>
before myFuction
, and what does it signify?
Considering the two functions:
public static void myFunction(List<?> list);
public static <T> void myFunction(List<T> list);
Please explain why we have included <T>
before myFuction
, and what does it signify?
When you use <?>
you are telling the virtual machine that you don't
know what type of object will be in the List, could one type could
be more than one type. List<?>
is the equivalent of List
from
previous 1.4 Java version when you could add to a list any type of
object and there was no constraint on that.
When you use <T>
you are defining a generic method. You are telling
the compiler that the List<T>
is a list of objet of type T
, which
will determined from the call to the method, but you enforce that
all object from List are of the same type, T
. You include <T>
before
the the function name to specify that you are defining a generic
method, and the compiler to know that T
should be treated as a type
and not as variable.