Thursday 13 March 2014

Lower Bounded Wildcards


? super Type
Here Type is the lower bound for the wild card “?”.

Ex:
printData(List<? super Integer> myList)
Above method can able to accept a list which is of type Integer and any other super class of Integer.

import java.util.*;
class LowerBoundWildCard{
 static void printData(List<? super Integer>  myList){
  for(Object obj : myList){
   System.out.print(obj +" ");
  }
  System.out.println();
 }
    
 public static void main(String args[]){
  List<Integer> l1 = new ArrayList<> ();
  l1.add(10);
  l1.add(20);
  l1.add(30);
      
  List<Object> l2 = new ArrayList<> ();
  l2.add("HI");
  l2.add(20);
  l2.add(l1);
      
  Number n1 = new Integer("10");
  Number n2 = new Byte("1");
  Number n3 = new Float("10.02");
  List<Number> l3 = new ArrayList<> ();
  l3.add(n1);
  l3.add(n2);
  l3.add(n3);
      
  System.out.println("Elements in list1 are " +l1);
  System.out.println("Elements in list2 are " + l2);
  System.out.println("Elements in list3 are " + l3);
 }
}



Output
Elements in list1 are [10, 20, 30]
Elements in list2 are [HI, 20, [10, 20, 30]]
Elements in list3 are [10, 1, 10.02]

Using Type Parameter “T” for lower bounds is restricted.



Since Number and Object are super classes for the Integer class, so printData() method can accept any type of list which is of type Integer, Number and Object.
 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment