Wednesday, February 13, 2008

Generics in Java

I have been working on collections for over an year now and have no idea of what generics are. Today I was going through the release notes of tiger java and I found out about them.

Generics are the type specification included in collections to get rid of unsafe code.

Prior to generics, compiler has no idea about what kinds of objects are stored in the collections and thus a runtime error is generated instead of a compile time error.

Generics are provided so that the collections can be checked by the compiler and reports errors for any inconsistencies in the code.

Prior to the introduction of generics ArrayList are used as

ArrayList list = new ArrayList();

This makes the code unclear as what is stored in ArrayList

To access the list each time the object has to be cast to a specified type and then consumed.

Whereas from java 1.5 ArrayList can be defined as

ArrayList list = new ArrayList();

This specifies that the list defined stores only values of type String. Thus making the code much more readable.Explicit casting is also not required as the compiler understands that the list contains

objects of type String.

courtesy: Generics

Help in identifying changes, corrections and violations would be greatly appreciated.