Java Wildcards

Java Wildcards:

The question mark (?) is known as the wildcard in generic programming . It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays, different instantiations of a generic type are not compatible with each other, not even explicitly.

Code:

  1. import java.util.List;  
  2. import java.util.ArrayList;  
  3.   
  4.   
  5. public class WildCardDemo {  
  6.   
  7.   
  8.     public static void main(String[] args) {  
  9.         // TODO Auto-generated method stub  
  10.   
  11.           
  12.         List<Integer>integerList=new ArrayList<Integer>();  
  13.         integerList.add(6);  
  14.         integerList.add(3);  
  15.         print(integerList);  
  16.           
  17.         List<String>sList=new ArrayList<String>();  
  18.         sList.add("A");  
  19.         sList.add("C");  
  20.         print(sList);     
  21.   
  22.     }  
  23.     public static void print(List<?> list) {  
  24.         for(Object input:list){  
  25.             System.out.println("Input "+input);  
  26.         }  
  27.   
  28.           
  29.     }  
  30.   
  31. }  


Share:

0 Comments:

Post a Comment