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