Chapter 8. Data Structuring with Generics, foreach, and Enumerations (JDK 1.5)
Introduction
JDK 1.5 introduced two new concepts, Generics and AutoBoxing/Unboxing, and two new language features, “foreach” and typesafe enumerations; these features are covered in this chapter.
Generics allow a class to be tailored for a variety of
argument/return types at compile time. It provides similar functionality
to the Templates mechanism that has been in C++ for some years. When
used with the Collections
classes
(see Chapter 7), Generics
significantly increase type safety and remove the requirement for downcasting
every object that is retrieved from a Collection
(either directly or via an Iterator
).
Recipe 5.3 discussed
the “Wrapper” classes; these classes provide Objects that represent
primitive values. Autoboxing automates the conversion from primitive to Object
and vice versa.
The new "foreach” mechanism does not give Java a new keyword; the
“for” keyword is still used. However, the syntax is changed slightly to
resemble the “for value in list” construct in languages such as the Unix
Bourne Shell and the Awk scripting language. This makes it much easier
to use Collections
, often eliminating
the need to obtain an Iterator
.
Finally, the Typesafe Enumerations feature provides a mechanism for dealing with a small list of discrete values, such as months, colors, and the like. It combines the enum syntax from Java’s predecessor, C, with the Typesafe Enumeration design pattern, giving JDK 1.5 ...
Get Java Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.