Why extends?

Java 5 introduced generics so you can use for example the collection framework without casts. But when and why you need to use wildcards?

Lets have a look at the following example:

public class Container<ELEMENT> implements Iterable<ELEMENT>
{
private final List<ELEMENT> elements = new ArrayList<ELEMENT>();

public Container(Iterable<ELEMENT> elements) {
for (ELEMENT e : elements) {
this.elements.add(e);
}
}

public Iterator<ELEMENT> iterator() {
return elements.iterator();
}

public int getSize() {
return elements.size();
}
}


Seems simple, but using it may become difficult:

public class ContainerTest
{
public void test() {
Container<Number> container = new Container<Number>(Arrays.asList(new Integer [] { new Integer(2), new Integer(1)}));
assertEquals(2, container.getSize());
}
}


The constructor is called with a List<Integer> which does not match an Iterable<Number> (the problem is nut the list but the integer).
Wildcards are the solution in this situation. Using wildcard you can write more universal but also typed code:

public class Container<ELEMENT>
{
...
public Container(Iterable<? extends ELEMENT> elements) {
...
}
...
}


Now the iterable of Integer In the example above will be accepted.