Home

This Chapter
-Appendix B: Generics
-Life without Generics
-Introducing Generic Types
-Using Generic Types without Type Parameters
-Using the ? Wildcard
-Using Bounded Wildcards in Methods
-Writing Generic Types

Table of Contents
-Introduction
-Chapter 1: Core Libraries
-Chapter 2: Dynamic Compilation
-Chapter 3: Scripting
-Chapter 4: Networking
-Chapter 5: Swing Updates
-Chapter 6: Abstract Window Toolkit
-Chapter 7: Internationalization
-Chapter 8: Java Database Connectivity 4.0
-Chapter 9: XML Digital Signature API
-Chapter 10: Streaming API for XML
-Chapter 11: Java Architecture for XML Binding
-Chapter 12: Web Services
-Chapter 13: JavaBeans Activation Framework
-Chapter 14: User-Defined MXBeans
-Chapter 15: Concurrency Updates
-Appendix A: Enums
-Appendix B: Generics
-Appendix C: Annotations

Previous
Next

 

Appendix B

Generics

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 appendix 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.

Previous
Next