10 April 2009

Generics and AutoBoxing


Another nice feature of Java is Generics and Auto Boxing introduced with version 5.

see how it simplifies things below:

assume we have a Hashtable that has String objects as keys and a Integer objects as the values.

With generic this is defined as

Hashtable errorList = new Hashtable();
errorList.put("error3",3); --autoboxing
Enumeration fileNames=errorList.keys();
while(fileNames.hasMoreElements()){
String name=fileNames.nextElement(); --no cast thx to generics
int info = errorList.get(name); --autoboxing
}


in the previous versions we would have to write

Hashtable err = new Hashtable();
err.put("error3", new Integer(3));
Enumeration enum4=err.keys();
while(enum4.hasMoreElements())
{
String name=(String)enum4.nextElement();
int info =((Integer)err.get(name)).intValue();
System.out.println(info);
}


Conclusion: I liked them both :)


No comments: