Upper bounded wildcard in generics

Upper bounded wildcard:

Upper bounded wildcard is used to restrict the unknown type to be a specific type or a subtype of that type using ‘?’ with extends keyword.
Syntax: Collectiontype<? extends T>
Let us consider that we want to write a method which prints square of each number in the list and work on List<Integer>, List<Double> and List<Number>. Normally we write it as:
public static void squareOfListItems(List list) {
for (Number num : list){
number = num.doubleValue();
System.out.println(num * num);
}
}
But this method will not work for List<Integer> and List<Double> because List<Integer> and List<Double> are not the subtypes of List<Number>. We can use upper bounded wild card to resolve this problem. List<? extends Number> matches a list of Number and any of its subtypes.
public static void squareOfListItems(List&lt;? extends Number&gt; list) {
for (Number num : list){
number = num.doubleValue();
System.out.println(num * num);
}
}
Note: In case of upper bound, new elements can’t be added in the collection. Elements are read only in case of upper bound. This is because we are using wild card in which type is unknown so we can’t guarantee that the newly added object have the correct type.

Upper bounded wildcard example:

GenericsTest.java
import java.util.ArrayList;
import java.util.List;
 
/**
* This class is used to show the use of Upper bounded wildcard.
* @author javawithease
*/

public class GenericsTest {
//Only work for the list of Number type.
static void squareOfListItems1(List list){
double number;
for (Number num : list){
number = num.doubleValue();
System.out.println(number * number);
}
}
 
//Work for Number and any of its sub types.
static void squareOfListItems2(List&lt;? extends Number&gt; list){
double number;
for (Number num : list){
number = num.doubleValue();
System.out.println(number * number);
}
}
 
public static void main(String args[]){
//Arraylist of Number type.
List list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
 
 
//Arraylist of Double type.
List list2 = new ArrayList();
list2.add(1.3);
list2.add(2.5);
list2.add(3.8);
 
//Only accept Number type list.
System.out.println("Square of List of Number " +
"type using squareOfListItems1 method:");
squareOfListItems1(list1);
 
//Accept Number and any of its sub types.
System.out.println("Square of List of Number " +
"type using squareOfListItems2 method:");;
squareOfListItems2(list1);
System.out.println("Square of List of Double " +
"type using squareOfListItems2 method:");
squareOfListItems2(list2);
 
}
}

Output:

Square of List of Number type using squareOfListItems1 method:
1.0
4.0
9.0
Square of List of Number type using squareOfListItems2 method:
1.0
4.0
9.0
Square of List of Double type using squareOfListItems2 method:
1.6900000000000002
6.25
14.44

No comments: