Chapter 5
Creating Generic Collection Classes
IN THIS CHAPTER
Discovering why the generics feature was invented
Using generics in your own classes
Working with wildcards in a generic class
Examining a pair of classes that demonstrate generics
In the previous two chapters, you’ve seen how you can specify the type for an ArrayList
or a LinkedList
so the compiler can prevent you from accidentally adding the wrong type of data to the collection. The ArrayList
and LinkedList
classes can do this because they take advantage of a feature called generics. Generics first became available in Java 1.5.
In this chapter, I show you how the generics feature works and how to put it to use in your own classes. Specifically, you see examples of two classes that use the LinkedList
class to implement a specific kind of collection. The first is a stack, a collection in which items are always added to the front of the list and retrieved from the front of the list. The second is a queue, a collection in which items are added to the end of the list and retrieved from the front.
Get Java All-in-One For Dummies, 5th 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.