?
extends Type
Here Type is the upper bound for the wild card “?”.
Lets say,
getSumOfElements(List<? Extends Number> myList)
Here Type is the upper bound for the wild card “?”.
Lets say,
getSumOfElements(List<? Extends Number> myList)
Number
is the upper bound for the wild card “?”. So the method can
accept List Of type Integer and all other sub classes of Number
class. Since Number is the upper bound for the wild card '?'.
import java.util.*; class UpperBoundWildCard{ static double getSumOfElements(List<? extends Number> myList){ double sum = 0; for (Number n : myList) sum += n.doubleValue(); return sum; } public static void main(String args[]){ List<Integer> l1 = new ArrayList<> (); l1.add(10); l1.add(20); l1.add(30); List<Double> l2 = new ArrayList<> (); l2.add(10.01); l2.add(20.01); l2.add(30.01); System.out.println("Sum of Integer List is " + (int)getSumOfElements(l1)); System.out.println("Sum of Double list is " +getSumOfElements(l2)); } }
Output
Sum of Integer List is 60 Sum of Double list is 60.03
Same Program can be re written using the Type parameter 'T' like below.
import java.util.*; class UpperBound{ static <T extends Number> double getSumOfElements(List<T> myList){ double sum = 0; for (Number n : myList) sum += n.doubleValue(); return sum; } public static void main(String args[]){ List<Integer> l1 = new ArrayList<> (); l1.add(10); l1.add(20); l1.add(30); List<Double> l2 = new ArrayList<> (); l2.add(10.01); l2.add(20.01); l2.add(30.01); System.out.println("Sum of Integer List is " + (int)getSumOfElements(l1)); System.out.println("Sum of Double list is " +getSumOfElements(l2)); } }
Output
Sum of Integer List is 60 Sum of Double list is 60.03
No comments:
Post a Comment