Java Reference
In-Depth Information
parameterized methods. Remember from Chapter 3 that you can use a parameter to
define a family of related tasks that differ just by a particular characteristic like
height or width. In this case, the parameter is a type and it is used to declare another
type. The type
ArrayList<E>
represents a family of types that differ just by the
type of element they store. You would use
ArrayList<String>
to store a list of
String
s,
ArrayList<Point>
to store a list of
Point
s,
ArrayList<Color>
to store
a list of
Color
s, and so on. Notice that you would never actually declare something
to be of type
ArrayList<E>
. As with any parameter, you have to replace the
E
with
a specific value to make it clear which of the many possible
ArrayList
types you
are using.
The
ArrayList
class is part of the
java.util
package, so to include it in a program
you must include an import declaration. The syntax for constructing an
ArrayList
is
more complicated than what we've seen before because of the type parameter. For
example, you would construct an
ArrayList
of
String
s as follows:
ArrayList<String> list = new ArrayList<String>();
This code constructs an empty
ArrayList<String>
. This syntax is complicated,
but it will be easier to remember if you keep in mind that the
<String>
notation is
actually part of the type: This isn't simply an
ArrayList
, it is an
ArrayList<String>
(often read as “an
ArrayList
of
String
”). Notice how the type appears when you
declare the variable and when you call the constructor:
ArrayList<String> list = new ArrayList<String>();
type
type
If you think in terms of the type being
ArrayList<String>
, you'll see that
this line of code isn't all that different from the code used to construct an object
like a
Point
:
Point p = new Point();
type
type
Once you've constructed an
ArrayList
, you can add values to it by calling the
add
method:
ArrayList<String> list = new ArrayList<String>();
list.add("Tool");
list.add("Phish");
list.add("Pink Floyd");
Search WWH ::
Custom Search