Thursday 13 March 2014

Unbounded Wildcards


Unbounded wild card is used for unknown types, for example, List<?>. This is called a list of unknown type.

/* Class demonstrates the use of Unbounded Wild Card */
import java.util.*;
 
class UnboundedWildCard{
 public static void printList(List<?> data){
  System.out.println("Elements in the List are");
  for(Object obj: data)
   System.out.print(obj +" ");
  System.out.println();
 }
   
 public static void main(String args[]){
  List<Integer> myList1 = new ArrayList<Integer> ();
  List<Double> myList2 = new ArrayList<Double> ();
      
  myList1.add(10);
  myList1.add(20);
  myList1.add(30);
      
  myList2.add(10.01);
  myList2.add(10.02);
  myList2.add(10.03);
      
  printList(myList1);
  printList(myList2);        
 }  
}
 



Output
Elements in the List are
10 20 30
Elements in the List are
10.01 10.02 10.03

As you see the prototype of the printList
printList(List<?> data)


'?' represents unknown type, So printList able to accepts any type of list.

 
 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment