Menu
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>();
            integerList.add(3);
            integerList.add(5);
            integerList.add(10);
            print(integerList);
            
            List<String> stringList = new ArrayList<String>();
            stringList.add("A");
            stringList.add("B");
            stringList.add("C");
            // 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 +" ");
            }
            
        }

}
OUTPUT

3 5 10

DESCRIPTION

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.

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

© meritcampus 2019

All Rights Reserved.

Open In App