14.2. Collections of Objects
In Chapter 13 you put together a generic type that defined a linked list. An object of type LinkedList<T> represented an example of a collection of objects of type T, where T could be any class or interface type. A collection is the term used to describe any object that represents a set of objects grouped together and organized in a particular way in memory. A class that defines collection objects is often referred to as a container class. A linked list is just one of a number of ways of organizing objects together in a collection.
There are three main types of collections that organize objects in different ways, called sets, sequences, and maps. Let's first get an understanding of how these three types of collections work in principle and then come back to look at the generic types that implement versions of these. One point I'd like to emphasize about the following discussion is that when I talk about a collection of objects, I mean a collection of references to objects. In Java, collections store references only—the objects themselves are external to the collection.
14.2.1. Sets
A set is probably the simplest kind of collection you can have. Here the objects are not ordered in any particular way at all, and objects are simply added to the set without any control over where they go. It's a bit like putting things in your pocket—you just put things in and they rattle around inside your pocket in no particular order. Figure 14-1 illustrates the idea ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 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.