Chris Webster's Weblog
Difference between extends and super In generic collections
The guidelines I have been using to differentiate when to use extends v. super are the following:
- Use extends if you need to read from the collection (i.e. List<? extends A>
. This will ensure that the collection itself contains items which extends A. This is read-only because there is no way to determine the exact type to add to the collection (the parameter could be List<B> and there would be no way of ensure the type safety of an addition). - Use super if you want to write to the collection (i.e. List<? super A>
. In this case, the collection can support addition of A types as we know the specified type of the collection is a super class of A. Therefore, A typed items can always be added to the collection.
Here is some code to look at:
import java.util.List;
public class GenericTest {
private void useExtends(List<? extends SomeInterface> l) {
for (SomeInterface i:l) {
}
// below doesn't compile because the exact type of list isn't known
l.add(new SomeInterface(){});
}
private void useSuper(List<? super SomeInterface> l) {
// the for loop below doesn't compile as the List is one of the super
// type of SomeInterface but unknown as to which one
// Object could be used in the for loop
for (SomeInterface i:l) {
}
l.add(new SomeInterface(){});
}
interface SomeInterface {}
}
Posted at 05:57PM Feb 11, 2007 by Christopher Webster in Java |
Sunday Feb 11, 2007