Click here to watch in Youtube :
https://www.youtube.com/watch?v=P1BxbW8tv8M&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
Java Tutorial: Generics in java | Java Generics [Upper bounded wildcard in Java Generics] |
import java.util.ArrayList;
import java.util.List;
public class GenericDemo1
{
public static void main(String[] args)
{
List<Number> numberList= new ArrayList<Number>();
numberList.add(2.2);
numberList.add(3.3);
numberList.add(5.5);
double sum = sum(numberList);
System.out.println("sum = " + sum);
List<Integer> integerList= new ArrayList<Integer>();
integerList.add(2);
integerList.add(3);
integerList.add(5);
sum = sum(integerList);
System.out.println("sum = " + sum);
}
public static double sum(List<Number> list)
{
double sum = 0;
for (Number n : list)
{
sum += n.doubleValue();
}
return sum;
}
}
OutputException in thread "main" java.lang.Error: Unresolved compilation problem:
The method sum(List<Number>) in the type GenericDemo1
is not applicable for the arguments (List<Integer>)
at GenericDemo1.main(GenericDemo1.java:20)
GenericDemo2.javaimport java.util.ArrayList;
import java.util.List;
public class GenericDemo2
{
public static void main(String[] args)
{
List<Number> numberList= new ArrayList<Number>();
numberList.add(2);
numberList.add(3);
numberList.add(5);
double sum = sum(numberList);
System.out.println("sum = " + sum);
List<Integer> integerList= new ArrayList<Integer>();
integerList.add(20);
integerList.add(33);
integerList.add(50);
sum = sum(integerList);
System.out.println("sum = " + sum);
}
public static double sum(List<? extends Number> list)
{
double sum = 0;
for (Number n : list)
{
sum += n.doubleValue();
}
return sum;
}
}
Outputsum = 10.0
sum = 103.0
Click the below link to download the code:
No comments:
Post a Comment