Menu
Topics Index
...
`

Generics Unbounded Wildcard - Java Example Program


Generics Unbounded Wildcard
import java.util.ArrayList;
import java.util.List;

class GenericsWithWildCardsDemo
{
        public static void main(String[] args)
        {
            List<Integer> integerList = new ArrayList<Integer>();
            integerList.add(6);
            integerList.add(3);
            integerList.add(10);
            print(integerList);
            System.out.println("\n----------");
            List<String> stringList = new ArrayList<String>();
            stringList.add("A");
            stringList.add("B");
            stringList.add("C");
            print(stringList);
        }
        public static void print(List<?> list)
        {
            for(Object input : list)
            {
                System.out.print(input +" ");
                //list.add(input); // LINE A
            }
        }
}
OUTPUT

6 3 10
----------
A B C

DESCRIPTION

If we uncomment the line at LINE A it gives compile time error since it does not allow to add anything to the list.

THINGS TO TRY
  • Create one more instance for list of doubles and invoke the print().

© meritcampus 2019

All Rights Reserved.

Open In App