Thursday 13 March 2014

Object Vs wild card (?)


Unbounded wild card is used for unknown types, can able to accept any kind of types. Will see it by an Example.

/* Class demonstrates the use of Unbounded Wild Card */
import java.util.*;
 
class ObjectVsWildCard{
 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.

/* Class demonstrates the use of Unbounded Wild Card */
import java.util.*;
 
class ObjectVsWildCard1{
 
 public static void printList(List<Object> 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);        
 }
}

When you tries tries to compile the above program, compiler throws the below error. Since List<Object> can't take List<Integer>, List<Double>. Where as List<?> takes any type of List.

ObjectVsWildCard1.java:25: error: method printList in class ObjectVsWildCard1 cannot be applied to given types;
                printList(myList1);
                ^
  required: List<Object>
  found: List<Integer>
  reason: actual argument List<Integer> cannot be converted to List<Object> by method invocation conversion
ObjectVsWildCard1.java:26: error: method printList in class ObjectVsWildCard1 cannot be applied to given types;
                printList(myList2);
                ^
  required: List<Object>
  found: List<Double>
  reason: actual argument List<Double> cannot be converted to List<Object> by method invocation conversion
2 errors
 
 



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment