Chapter 7. Collections and Generics

As we start to use our growing knowledge of objects to handle more and more interesting problems, one recurring question will emerge. How do we store the data we’re manipulating in the course of solving those problems? We’ll definitely use variables of all the different types, but we’ll also need bigger, fancier storage options. The arrays we discussed back in “Arrays” are a start, but arrays have some limitations. In this chapter we will see how to get efficient, flexible access to large amounts of data using Java’s idea of collections. We’ll also see how to deal with the various types of data we want to store in these big containers like we do with individual values in variables. That’s where generics come in. We’ll get to those in “Type Limitations”.

Collections

Collections are data structures that are fundamental to all types of programming. Whenever we need to refer to a group of objects, we have some kind of collection. At the core language level, Java supports collections in the form of arrays. But arrays are static, and because they have a fixed length, they are awkward for groups of things that grow and shrink over the lifetime of an application. Arrays are also bad at representing abstract relationships between objects. In the early days, the Java platform had only two basic classes to address these needs: the java.util.Vector class, which represents a dynamic list of objects, and the java.util.Hashtable class, which holds a map of ...

Get Learning Java, 6th 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.