Search⌘ K

Bounded Types

Explore how to apply bounded types in Java generics to restrict type parameters, ensuring they extend a specific class like Number. Understand how this technique enhances type safety and avoids runtime exceptions, allowing you to invoke methods such as intValue() without casting.

We'll cover the following...
1.

What are bounded type parameters?

Show Answer
Did you find this helpful?
Java
import java.util.ArrayList;
import java.util.List;
class Demonstration {
public static void main( String args[] ) {
NumberCollection<Integer> myIntegerList = new NumberCollection<>();
myIntegerList.add(5);
myIntegerList.add(4);
myIntegerList.printGreater(4);
}
}
class NumberCollection<T> {
List<T> list = new ArrayList<>();
// Method compares integer portions of each
// value stored in the list and prints those
// that are greater than the method argument
public void printGreater(T other) {
for (T item : list) {
// crude way to get integer portions
int val1 = Double.valueOf(item.toString()).intValue();
int val2 = Double.valueOf(other.toString()).intValue();
if (val1 > val2)
System.out.println(item);
}
}
public void add(T item) {
list.add(item);
}
}

We can fix the above situation by bounding the type parameter T to only be a subclass of Number. This eliminates the possibility of runtime exceptions that can result if the ...