Sunday Feb 11, 2007

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 {}
   
}
 



About

cwebster

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today