Tuesday 16 May 2017

Java Tutorial: Generics in java | Java Generics [Upper bounded wildcard in Java Generics]


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] 
GenericDemo1.java
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;
    }

}
Output
Exception 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.java
import 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;
    }

}
Output
sum = 10.0
sum = 103.0
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_upper_bounded_wildcard_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_upper_bounded_wildcard_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/539015917c8406e4be671410d713073b3971d1a5/BasicJava/GenericsDemo_upper_bounded_wildcard_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment