Generics helps to write code in easy way.
-Generics makes code robust by adding strong type check at compile time check.
- Casting is not required as you define type while creating objects.
There is very important point to note related to Generics and Inheritance concept of OOPS.
Consider following java class:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestGenericList {
/**
* @param args
*/
public static void main(String[] args) {
List< String > strList = new ArrayList < String >();
strList .add("a");
strList .add("b");
strList .add("c");
TestGenericList t = new TestGenericList();
// Can we use below code to call printList?
// t.printList(strList );
}
public void printList(List < Object > list ){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}
}
}
We know that String extends Object so you assume that you can pass strList object to printList function.
WRONG
You can not pass strList to printList function as function accept list of Object.
Even though String extends Object but List does not extend List< Object >
You can refer java tutorials for more details at:
http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html
-Generics makes code robust by adding strong type check at compile time check.
- Casting is not required as you define type while creating objects.
There is very important point to note related to Generics and Inheritance concept of OOPS.
Consider following java class:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestGenericList {
/**
* @param args
*/
public static void main(String[] args) {
List< String > strList = new ArrayList < String >
strList .add("a");
strList .add("b");
strList .add("c");
TestGenericList t = new TestGenericList();
// Can we use below code to call printList?
// t.printList(strList );
}
public void printList(List < Object > list ){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}
}
}
We know that String extends Object so you assume that you can pass strList object to printList function.
WRONG
You can not pass strList to printList function as function accept list of Object.
Even though String extends Object but List
You can refer java tutorials for more details at:
http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html