Chapter 17. Generic Programming

CHAPTER GOALS

  • To understand the objective of generic programming

  • To be able to implement generic classes and methods

  • To understand the execution of generic methods in the virtual machine

  • To know the limitations of generic programming in Java

Generic programming involves the design and implementation of data structures and algorithms that work for multiple types. You are already familiar with the generic ArrayList class that can be used to collect elements of arbitrary types. In this chapter, you will learn how to implement your own generic classes.

Generic Classes and Type Parameters

Generic programming is the creation of programming constructs that can be used with many different types. For example, the Java library programmers who implemented the ArrayList class used the technique of generic programming. As a result, you can form array lists that collect elements of different types, such as Array-List<String>, ArrayList<BankAccount>, and so on.

The LinkedList class that we implemented in Section 15.2 is also an example of generic programming—you can store objects of any class inside a LinkedList. That LinkedList class achieves genericity by using inheritance. It uses references of type Object and is therefore capable of storing objects of any class. In contrast, the Array-List class is a generic class: a class with a type parameter that is used to specify the type of the objects that you want to store. (Note that only our LinkedList implementation of

Get Big Java, 4th 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.