Bounded Types
This lesson discusses bounded types in Java's generics.
We'll cover the following...
We'll cover the following...
1.
What are bounded type parameters?
0/500
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 argumentpublic void printGreater(T other) {for (T item : list) {// crude way to get integer portionsint 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 ...