Consider following methods:
public static void listAll(LinkedList list) {
for(Object obj : list)
System.out.println(obj);
}
and
public static void listAll(LinkedList<?> list) {
for(Object obj : list)
System.out.println(obj);
}
What is the difference between these two methods? If there is no difference, why we should use the second one?
<?>
doesn't allow you to add objects in list. See the program below. It is specific type of list we have passed to method<?>
.Specific means, list was created with specific type and passed to
<?>
methodlistAll
. Don't confuse with wordspecific
.Specific can be any normal object, like, Dog, Tiger, String, Object, HashMap, File, Integer, Long.... and the list is endless.
JLS
forces<?>
method for not to perform add anyirrelevant objects
in called<?>
method once you have defined (defined in calling method not incalled-listAll
) list containingspecific type
of object.It is like
<?>
saying "don't touch me".Now let's look at the different scenario. What will happen when we declare specific type like, Dog, Tiger, Object, String ..... anything. Let's change the method to
specific type
.List
is a raw type,List<?>
is a generic type with wildcard argument.Suppose that we have the following variables:
The assignment
b=a
gives a compile-time error (aList<String>
is not assignable toList<?
), butc=a
compiles fine (List<String>
is assignable to the raw typeList
for compatibility with legacy code not using generics).The assignment
b=c
gives a compile-time warning (List<?>
is not assignable toList<String>
), buta=c
compiles fine (List<String>
is assignable toList<?>
)