Specifying upper bound with
extends
// drawAll() can draw a list of shapes as well as a list of subtype of
// shapes
public static void drawAll(Collection<? extends Shape> shapes) {
for (Shape s : shapes) {
s.draw();
}
}
public static void main(String[] args) {
// create a list of triangles
List<Triangle> triangles = new ArrayList<Triangle>();
// add triangle1 to triangle list
Triangle t1 = new Triangle();
triangles.add(t1);
// add triangle2 to triangle list
Triangle t2 = new Triangle();
triangles.add(t2);
// call drawAll() to draw a list of triangles
drawAll(triangles);
}
Specifying lower bound with super
// finding the max value
// T implements Comparator of super type of T
public static <T extends Comparator<? super T> > T max( T[] arr ) {
if (arr == null || arr.length == 0)
throw new IllegalArgumentException();
T m = arr[0];
int len = arr.length;
for (int i = 1; i < len; i++) {
if ( m.compare(m, arr[i]) < 0 )
m = arr[i];
}
return m;
}