Java Reference
In-Depth Information
In our daily lives, we often manipulate lists of one kind or another. For example, on
social networking sites like Facebook.com, people list the bands they like. Suppose
someone listed the following bands:
Tool, U2, Phish, Pink Floyd, Radiohead
You saw in Chapter 7 that you can declare an array to store a sequence of values.
For example, to store the preceding list, you could declare an array of
String
s of
length 5. But what happens if you want to change the list later (say, to remove Tool
and U2 from the list)? You would have to shift values over, and you'd be left with
empty array slots at the end. And what if you wanted to add to the list, so that it
ended up with more than five names? You wouldn't have room to store more than five
values in the original array, so you would have to construct a new array with a larger
size to store the list.
Most of us think of lists as being more flexible than that. We don't want to have to
worry about the kind of low-level details that come up in the course of manipulating
an array. We want to be able to just say, “Add something to the list” or “Remove this
value from the list,” and we want the lists to grow and shrink over time as we add or
remove values. Computer scientists would say that we have in mind a
list abstraction
that enables us to specify certain operations to be performed (add, remove) without
having to worry about the details of how those operations are performed (shifting,
constructing new arrays).
Java provides this functionality in a class called
ArrayList
. Internally, each
ArrayList
object uses an array to store its values. As a result, an
ArrayList
pro-
vides the same fast random access as an array. But unlike with an array, with an
ArrayList
you can make simple requests to add or remove values, and the
ArrayList
takes care of all of the details for you: If you add values to the list it
makes the array bigger, and if you remove values it handles any shifting that needs to
be done.
Remember that you can declare arrays of different types. If you want an array of
int
values, you declare a variable of type
int[]
. For an array of
String
values, you
use the type
String[]
. This is a special syntax that works just for arrays, but the
ArrayList
class has almost the same flexibility. If you read the API documentation
for
ArrayList
, you'll see that it is actually listed as
ArrayList<E>
. This is an
example of a
generic class
in Java.
Generic Class (Generic)
A class such as
ArrayList<E>
that takes a type parameter to indicate what
kind of values it will use.
The “E” in
ArrayList<E>
is short for “Element,” and it indicates the type of
elements that will be included in the
ArrayList
. Generic classes are similar to
Search WWH ::
Custom Search