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.5Example
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);
}
}
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.
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 wellExample
ArrayList<? super Integer> numberList = new ArrayList();numberList = new ArrayList();
numberList = new ArrayList();
No comments:
Post a Comment