Generics are the most important feature in Java 5. They enable you to write a type (a class or an interface) and create an instance of it by passing a reference type or reference types. The instance will then be restricted to only working with the type(s). For instance, the java.util.List interface has been made generic in Java 5. When creating a List object, you pass a Java type to it and produce a List instance that can only work with objects of that type. That is, if you pass java.lang.String, the List instance can only hold String objects; if you pass java.lang.Integer, the instance can only store Integer objects. In addition to parameterized types, you can create parameterized methods too.
The first benefit of generics is stricter type checking at compile time . This is most apparent in the Collections Framework. In addition, generics eliminate most type castings you had to perform when working with the Collections Framework in pre-5 Java releases.
This chapter teaches you how to use and write generic types. It starts with the section “Life without Generics”, which reminds us what we missed in earlier versions of JDK’s. Then, it presents some examples of generic types. After the discussions of the syntax and the use of generic types with bounds, this chapter concludes with a section that explains how to write generic types.