Topics Index

Generics Upper Bounded Wildcard - Java Example Program

Generics Upper Bounded Wildcard
import java.util.ArrayList;
import java.util.List;

class GenericsWithWildCards
        public static void main(String[] args)
            List<Integer> integerList = new ArrayList<Integer>();
            List<String> stringList = new ArrayList<String>();
            // print(stringList); // LINE A
        // public static void print(List<Number> list) // LINE B
        public static void print(List<? extends Number> list) // LINE C
            for(Number input : list)
                System.out.print(input +" ");


3 5 10


Here uncomment the line at LINE Band comment the line at LINE Cit gives compile time error. It won’t work with List of Integers or Doubles because we know that List<Integer> and List<Double> are not related, this is when upper bounded wildcard is helpful. We use generics wildcard with extendskeyword and the upper bound classor interfacethat will allow us to pass argument of upper bound or it’s subclasses types. Uncomment the LINE A it gives compile time error, since String class does not come under Number class.

  • Create one more object for Double and invoke print() method.

© meritcampus 2019

All Rights Reserved.

Open In App