Home

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

Table of Contents
-Introduction
-Chapter 1: Your First Taste of Java
-Chapter 2: Language Fundamentals
-Chapter 3: Statements
-Chapter 4: Objects and Classes
-Chapter 5: Core Classes
-Chapter 6: Inheritance
-Chapter 7: Error Handling
-Chapter 8: Numbers and Dates
-Chapter 9: Interfaces and Abstract Classes
-Chapter 10: Enums
-Chapter 11: The Collections Framework
-Chapter 12: Generics
-Chapter 13: Input Output
-Chapter 14: Nested and Inner Classes
-Chapter 15: Swing Basics
-Chapter 16: Swinging Higher
-Chapter 17: Polymorphism
-Chapter 18: Annotations
-Chapter 19: Internationalization
-Chapter 20: Applets
-Chapter 21: Java Networking
-Chapter 22: Java Database Connectivity
-Chapter 23: Java Threads
-Chapter 24: Security
-Chapter 25: Java Web Applications
-Chapter 26: JavaServer Pages
-Chapter 27: Javadoc
-Chapter 28: Application Deployment
-Appendix A: javac
-Appendix B: java
-Appendix C: jar
-Appendix D: NetBeans
-Appendix E: Eclipse

Previous
Next

 

Chapter 12

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

Previous
Next