Home  >  Core Java

Example of Wildcards in Java Generics

By Arvind Rai, 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);
      }
}
 
In the above code snippet List can accept any object. So we have to use Object class for further processing for the given input object. If we want to restrict the type of object by a super class, it can be done as
void display(List<? extends SuperClass> col) {
      for (Object ob : col) {
        System.out.println(ob);
      }
}
 
Here SuperClass is a class defined by us. Now we can pass only those objects list which is extending the class SuperClass. Find the example.

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);
      }
  }
}
 
Output:
Display method is Printing Integer
1
2
Display method is Printing String
A
B
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us