Java Reference
In-Depth Information
13.1 Collections and Data Structures
A collection is an object that serves as a repository for other objects. It is a generic
term that can be applied to many situations, but we usually use it when discussing
an object whose specific role is to provide services to add, remove, and otherwise
manage the elements that are contained within. For example, the ArrayList class
(discussed in Chapter 5) represents a collection. It provides methods to add ele-
ments to the end of a list or to a particular location in the list based on an index
value. It provides methods to remove specific elements as needed.
Some collections maintain their elements in a specific order, while others do not.
Some collections are
homogeneous, meaning that they can contain all of the same
type of object; other collections are
heterogeneous, which means they can contain
objects of various types. An ArrayList that doesn't specify an explicit element type
can be thought of as heterogeneous because it can hold an object of any type. Its
heterogeneous nature comes from the fact that an ArrayList stores Object refer-
ences, which means it can store any object because of inheritance and polymorphism.
Separating Interface from Implementation
A crucial aspect of collections is that they can be implemented in a variety of ways.
That is, the underlying data structure that stores the objects can be implemented
using various techniques. The ArrayList class from the Java standard library,
for instance, is implemented using an array. All operations on an ArrayList are
accomplished by invoking methods that perform the appropriate operations on
the underlying array.
An abstract data type (ADT) is a collection of data and the particular opera-
tions that are allowed on that data. An ADT has a name, a domain of values, and
a set of operations that can be performed. An ADT is considered abstract, because
the operations you can perform on it are separated from the underlying imple-
mentation. That is, the details of how an ADT stores its data and accomplishes
its methods are separate from the concept that it embodies. Essentially, the terms
collection and abstract data type are interchangeable.
Objects are perfectly suited for defining collections. An object, by definition,
has a well-defined interface whose implementation is hidden in the
class. The way the data is represented, and the operations that man-
age the data, are encapsulated inside the object. This type of object
is reusable and reliable, because its interaction with the rest of the
system is controlled.
KEY CONCEPT
An object, with its well-defined
interface, is a perfect mechanism for
implementing a collection.
 
Search WWH ::




Custom Search