Saturday, October 4, 2008

Using and Programming Generics in J2SE 5.0

 A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. It is your responsibility, however, to keep track of what types of objects your collections contain. As an example, consider adding an int to a collection; since you cannot have collections of primitive data types you must convert the int to the corresponding reference type (i.e. Integer) before storing it in the collection. Now, when the element is extracted from the collection an Object is returned that must be cast to an Integer in order to ensure type safety. All this makes Java programs unnecessarily hard to read and maintain, and are more likely to fail with runtime errors.
If the compiler could keep track of the element type, you do not need to keep track of what collections you have and the need for casting would be eliminated. This would make programs easier to read and maintain, and less likely to fail at runtime. J2SE 5.0 has added a new core language feature known as generics (also known as parameterized types), that provides compile-time type safety for collections and eliminate the drudgery of casting. The effort of adding generics to Java is led by Sun Microsystems as JSR 14 under the Java Community Process (JCP).
Generics are one of the most frequently requested language extensions to Java, and they have been finally added in J2SE 5.0. This article provides an introduction to programming with generics.
The Need for Generics
The motivation for adding generics to the Java programming language stems from the lack of information about a collection's element type, the need for developers to keep track of what type of elements collections contain, and the need for casts all over the place. Using generics, a collection is no longer treated as a list of Object references, but you would be able to differentiate between a collection of references to Integers and collection of references to Bytes. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection.

Click Here To Read More

No comments: