Searching...
Thursday, 20 September 2012

Java generics Example

05:06

Java Generics

Java Generics are a language feature that allows for definition and use of generic types and methods. It is a compilation feature introduced in java 1.5

Example

package com.vinod.test;

import java.util.ArrayList;

public class GenericsTest {
    public static void main(String[] args) {
        ArrayList vlist = new ArrayList();
        vlist.add("Pretech Learning");
        Integer vint = (Integer) vlist.get(0);
        System.out.println(vint);
    }

}
  

Output

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.vinod.test.GenericsTest.main(GenericsTest.java:9)

The compilation of above program is successful but during the run time we will get class caste exception has occured to avoid this introduced Java Generics, see if we are creating an arraylist and defining the type as String.
package com.vinod.test;

import java.util.ArrayList;

public class GenericsTest {
    public static void main(String[] args) {
        ArrayList<String> vlist = new ArrayList<String>();
        vlist.add("Pretech Learning");
        Integer vint = (Integer) vlist.get(0);
        System.out.println(vint);
    }

}
In this above case compiler will shows the error before running the program.

What is ? Extends and ? Super

First see this below class hierarchy (example) Here Number is the super class of all other classes except Object class

<? Extends E>

The first example we restricted as the Arraylist for only String. Whenever we want define the type as its sub class as well we can use <? Extends E>

Example

 ArrayList<? extends Number> numberList = new ArrayList();
                  numberList = new ArrayList();
                  numberList = new ArrayList();
Here we define as ? extents Number so we can create the type as its subclass Integer and Float.

<? Super E>

The same way we can use it for super class as well

Example

         ArrayList<? super Integer> numberList = new ArrayList();
                  numberList = new ArrayList();
                  numberList = new ArrayList();

0 comments: