Generics and Bounds
Generic Bounds
- Generic classes can be bounded with a certain type
- 2 bound forms in Generics
- Upperbound
- uses extends keyword
- limits the states that the accepted type must be a subtype of the given class
- Lowerbound
- uses the super keyword
- limits the states that the accepted type must be a supertype of the given class
- Upperbound
Sample Codes
Upper Bound
public <T extends Number> T max(T[] elements){
if(elements.length <= 0)
return null;
T curr = elements[0];
for(int i=1; i<elements.length; i++){
if(curr.compareTo(elements[i]) < 0){
curr = elements[i];
}
}
return curr;
}On the example above, the possible types that can be accepted by method will be limited to all subclasses of the Number class
Lower Bound
public<T, S super T> S[] copy(T[] src, S[] dest){
for(int i=0; i<src.length; i++){
dest[i] = src[i];
}
return dest;
}On the example above, the destination collection will only accept the superclass types of T. This is useful when arguments needs to be reordered. If we try to use upperbound limit, the type will be limited by a specific type.