Wednesday 25 February 2015

Generics in Java

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than runtime.
List<Integer> list = new ArrayList<Integer>();
list.add("hello");//Compile Time Error
list.add(32);

----
more you can refer from:-
http://www.javatpoint.com/generics-in-java

for better and deep understanding must use this link:-
http://javarevisited.blogspot.in/2011/09/generics-java-example-tutorial.html

No comments:

Post a Comment