I know that there was a similar question already posted, although I think mine is somewhat different...
Suppose you have two methods:
// Bounded type
I can think of the below differences :
a) Modifying your list inside the method, consider below code :
private static void processList(List someList)
{
T t = someList.get(0);
if ( t.getClass() == Integer.class )
{
Integer myNum = new Integer(4);
someList.add((T) myNum);
}
}
// Upper bound wildcard
private static void processList2(List extends Number> someList)
{
Object o = someList.get(0);
if ( o instanceof Integer )
{
Integer myNum = new Integer(4);
someList.add(myNum); // Compile time error !!
}
}
With wildcard you cannot add elements to the list ! Compiler tells you that it doesn't know what is myNum
. But in the first method, you could add a Integer
by first checking if T
is Integer
, no compile time error.
b) The first method is called generic method. It follows the syntax that is defined for a generic method. The upper bounds specified in the method definition are used to restrict the parameter types.
The second one is NOT necessarily called a generic method, it is a normal method that happens to accept a generic parameter.
The wildcard ?
with extends
keyword is used as a means of relaxing the types that the method can accept.