For a generic interface:
public interface Foo {
void f(T t);
}
The difference between the two fields:
publ
The wildcard in Foo>
indicates that within the current scope, you don't know or care what type of 'Foo' you have.
Foo>
and Foo extends Object>
are the same (the first is shorthand for the other). Foo
is different.
A concrete example:
You can assign any sort of List
to List>
e.g.
List> list1 = new ArrayList();
List> list2 = new ArrayList
If you have a List>
you can call size()
because you don't need to know what type of list it is to find out its size. And you can call get(i)
because we know that the list contains some sort of Object
, so the compiler will treat it as if get
returns and Object
.
But you can't call add(o)
because you don't know (and the compiler doesn't know) what sort of list you're dealing with.
In our example above you wouldn't want to allow list1.add(new Object());
because that's supposed to be a list of String
s
The reason for wildcards is so you can do things like this:
public static boolean containsNull(List> list)
{
for(Object o : list )
{
if( o == null ) return true;
}
return false;
}
That code can work on any sort of list that you want, a List
, List
, List
, etc.
If the signature was public static boolean containsNull(List
then you could only pass List
to it, List
wouldn't work.