Generics - Wild Card Arguments

With generics, type safety is ensured. At the same time, it can cause you to write reduntant code even in acceptable scenarios.

Consider the below code :

public class WildCardExample {
    public static void main(String[] args) {
        ArrayList<String> strList = new ArrayList<String>();        strList.add("1");        strList.add("2");        strList.add("Sandeep");
        ArrayList<Integer> intList = new ArrayList<Integer>();        intList.add(1);        intList.add(2);        intList.add(3);
        ArrayList<Double> doubleList= new ArrayList<Double>();        doubleList.add(1.1);        doubleList.add(1.2);
        System.out.println("Printing string list : ");        printValue(strList);        System.out.println("Printing int list : ");        printValue(intList);        System.out.println("Printing double list : ");        printValue(doubleList);    }

      public static void printValue(ArrayList<String> inputValues) {            for(int i=0; i<inputValues.size();i++) {
                System.out.println(inputValues.get(i));            }
        }
}

The above code will give a compilation error since printValue() only accepts ArrayList<String> as a parameter.

To solve this, you may actually think to overload the printValue() method with ArrayList<Integer> and ArrayList<Double> parameter types.

With generics, we have the option of wildcard arguments which can solve this without the need of overloading.

public static void printValue(ArrayList<?> inputValues) {
    for(int i=0; i<inputValues.size();i++) {
        System.out.println(inputValues.get(i));    }
}

Here, ArrayList<?> matches any ArrayList object.

The code for the above example can be found here

Wild card arguments also support boundaries in the following ways :

1. Upper bound :
       <? extends superclass>

In this case, only the classes that are inherited from superclass, are acceptable arguments.

2. Lower bound :
       <? super subclass>

In this case, only the classes that are superclass of the subclass, are acceptable arguments.

Try the following ways of using wildcard arguments :

ArrayList<?> list1 = new ArrayList<?>();ArrayList<?> list2 = new ArrayList<Object>();ArrayList<? extends Object> list3 = new ArrayList<String>();ArrayList<? super String> list4 = new ArrayList<Object>();ArrayList<? super String> list5 = new ArrayList<Integer>();

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures