Java 101Using bounded type parameters in generic methods

time to read 1 min | 114 words

Sometimes it may be appropriate to write a generic method, however it will not be possible for it to accept every type while still maintaining all the necessary functionality.

To solve this, use bounded type parameters to restrict generic methods from accepting arguments of a particular kind.

public <T extends Shape> 
  void drawAll(List<T> shapes){
    for (Shape s: shapes) {
        s.draw(this);
    }
}

The above method is used to draw a list of shapes. Writing a generic method with an unbounded type parameter would cause problems because lists of other types cannot be drawn in this way.

By specifying that <T extends Shape> we guarantee that only Shape objects can be passed to the method.