Example of Wildcards in Java Generics
October 31, 2013
Wildcards (?) helps to create such method that can work for more than one type of object.Here ? means unknown object type. Simple generic declarations limit us to use only one type of object. Wildcards (?) supports use in the scenario where we are not sure for the object type.
The typical Wildcards declaration is given below
void display(List<?> col) { for (Object ob : col) { System.out.println(ob); } }
void display(List<? extends SuperClass> col) { for (Object ob : col) { System.out.println(ob); } }
GenericMethodDemo.java
package com.concretepage; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class GenericMethodDemo { public static void main(String[] args) throws IOException { System.out.println("Display method is Printing Integer"); List<Integer> intList = new ArrayList<Integer>(); intList.add(1); intList.add(2); display(intList); System.out.println("Display method is Printing String"); List<String> strList = new ArrayList<String>(); strList.add("A"); strList.add("B"); display(strList); } static void display(List<?> col) { for (Object ob : col) { System.out.println(ob); } } }
Display method is Printing Integer 1 2 Display method is Printing String A B