Thursday, 14 May 2015

Lower Bound in Java With Example

Lower Bound in Java With Exampl

You can use an lower bounded wildcard to put the restrictions on a variable. For example, say you want to write a method that works on List<Integer>,List<Number> and List<Object> or — anything that can hold Integer values. Only; you can achieve this by using lower bounded wildcard.

To declare an lower-bounded wildcard, use the wildcard character ('?'), followed by the super keyword, followed by its lower bound.

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. The termList<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.

Consider the following showNumbers method for Example:

we have used List<? super Integer> which will allow us to pass list of all the Call which is super class of Integer. so here when you call showNumbers Method then you can pass List of type List<Integer>, List<Number>, List<Object>.


import java.util.*;
public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        List<Object> li=new ArrayList<Object>();
       
        for (int i = 1; i <= 10; i++) {
        li.add(i);
        }
    HelloWorld.addNumbers(li);
       
     }
    
     public static void addNumbers(List<? super Integer> list) {
    for (int i = 0; i <= list.size()-1; i++) {
         System.out.println(list.get(i));
         }
}
}

No comments:

Post a Comment