img
Generics
S
ince the original 1.0 release in 1995, many new features have been added to Java. The one
that has had the most profound impact is generics. Introduced by JDK 5, generics changed
Java in two important ways. First, it added a new syntactical element to the language.
Second, it caused changes to many of the classes and methods in the core API. Because generics
represented such a large change to the language, some programmers were reluctant to adopt its
use. However, with the release of JDK 6, generics can no longer be ignored. Simply put, if you
will be programming in Java SE 6, you will be using generics. Fortunately, generics are not
difficult to use, and they provide significant benefits for the Java programmer.
Through the use of generics, it is possible to create classes, interfaces, and methods that
will work in a type-safe manner with various kinds of data. Many algorithms are logically the
same no matter what type of data they are being applied to. For example, the mechanism that
supports a stack is the same whether that stack is storing items of type Integer, String, Object,
or Thread. With generics, you can define an algorithm once, independently of any specific
type of data, and then apply that algorithm to a wide variety of data types without any additional
effort. The expressive power generics add to the language fundamentally changes the way
that Java code is written.
Perhaps the one feature of Java that has been most significantly affected by generics is
the Collections Framework. The Collections Framework is part of the Java API and is described
in detail in Chapter 17, but a brief mention is useful now. A collection is a group of objects.
The Collections Framework defines several classes, such as lists and maps, that manage
collections. The collection classes have always been able to work with any type of object.
The benefit that generics add is that the collection classes can now be used with complete
type safety. Thus, in addition to providing a powerful, new language element, generics also
enabled an existing feature to be substantially improved. This is why generics represent such
an important addition to Java.
This chapter describes the syntax, theory, and use of generics. It also shows how generics
provide type safety for some previously difficult cases. Once you have completed this chapter,
you will want to examine Chapter 17, which covers the Collections Framework. There you
will find many examples of generics at work.
REMEMBER  Generics were added by JDK 5. Source code using generics cannot be compiled by
EMEMBER
earlier versions of javac.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home