Generics Wildcard in java

Types of Generics Wildcard
  • Bounded
    Bounded wildCard can be written in two ways upper bound and lower bound.<? super T> and <? extends T> are bounded wildcards respectively.
    • <? extends T> where all types must be sub class of T type .
    • <? super T> where all types must be super class of T type.
    • Unbounded
      <?> denotes unbounded wildcards which can allow any Type.

Example to show Wildcard

import java.util.ArrayList;
import java.util.List;
public class WildcardDemo {
	//As it is a unbounded wildcard it can take anything
	public void print(List<?> list)	
	{
		System.out.println(list);
	}
	//This method take only those which extends the 
	//Number class,it is a bounded wildcard
	public void printNumber(List<? extends Number> list)	
	{
		System.out.println(list);
	}
	//This method take only those which extends the Object class
	public void printObject(List<? extends Object> list)	 
	{
		System.out.println(list);
	}
	public static void main(String[] args) {
		List<String> string = new ArrayList<String>();
		List<Integer> integer=new ArrayList<Integer>();
		string.add("hi");
		string.add("hello");
		string.add("bye");
		
		integer.add(111);
		integer.add(222);
		integer.add(333);
		WildcardDemo wd=new WildcardDemo();
		wd.print(string);
		wd.print(integer);
		wd.printNumber(integer);
		wd.printObject(string);
		wd.printObject(integer);	
	}
	}