Thursday, April 10, 2008

Java Generics -- Part1

Java Generics provided with JDK5.0 "tiger" is a very powerful feature. It provides following solutions.
  1. Code readability
  2. Robustness
  3. A way to provide type of collection to compiler.
    Consider following code


public static java.util.Vector getNumbers(){
Vector vec=new Vector();
vec.addElement(new Integer(10));
vec.addElement(new Float(2.5F))
return vec;
}

public static void main(String[] kmj){
Vector vec=getNumbers();
int size=vec.size();
for( int i=0;i<size;i++){
Integer int=(Integer) vec.elementAt(i);
}}

If you compile above programme it compiles successfully but at runtime it fails. Now a obvious question may be that if a developer is writing code himself then he will be aware of code but at the same time consider a case where a large project is executed and work is divided into modules so it is always possible that you will not be aware of code and will call method directly.
Another case is where you have a large programm and you do not have much documentation available for code and at many places you have methods which return Collections. In this case it is very difficult to identify , what Type of object a particular collection contains, in such scenarios java Generics help you a lot as it increases code redability. Consider following code

public static java.util.Vector getNumbers(){

Vector vec=new Vector();
vec.addElement(new Integer(10));
vec.addElement(new Float(2.5F)) // Compilation Error
return vec;
}
public static void main(String[] kmj){
Vector vec=getNumbers();int size=vec.size();
for( int i=0;i<size;i++){
Integer int=vec.elementAt(i);
}}

This code provides additional advantage over code wirtten above.

This does tells you at compile time only that you code is not type safe. One can have argument that collection should store all type of object. From my point of view Collection are not there for storing multiple type of objects but they are for storing multiple Objects of same Type and help to mange those Object properly.

Another advantage of above code is that , after looking at method signatures one can identify that what Type of objects , returned collection contains.

No comments:

Post a Comment