Java Reference
In-Depth Information
Why Are Some Parameters of Type
Base_Type
and Others
of Type
Object
?
Look at the table of methods in Display 14.1. In some cases, when a parameter is naturally
an object of the base type, the parameter type is the base type, but in other cases, it is the
type
Object
.
For example, look at the
add
methods and the second
remove
method in the table. The
add
methods have a parameter of the base type; the
remove
method has a parameter of
type
Object
. Why the difference in parameter types? The class
ArrayList
implements a
number of interfaces and inherits methods from various ancestor classes. These interfaces
and ancestor classes specify that certain parameters have type
Object
.
For example, in Chapter 7, we explained that the parameter for the
equals
method is
always of type
Object
because the method heading is inherited from the class
Object
.
In other cases, the designers of the
ArrayList
class were free to specify the parameter
types for the method.
The “for-each” Loop
In Chapter 16, we will cover a family of classes known as
collections
. The
ArrayList
classes are our first examples of collection classes. Starting with version 5.0, Java has
added a new kind of
for
loop that can cycle through all the elements in a collection
and can, in particular, cycle through all the elements in an
ArrayList
. This new kind
of
for
loop is called a
for-each loop
or
enhanced for loop
. A for-each loop can also
be used to cycle through all the elements in an array. The for-each loop was introduced
for use with arrays in a starred section of Chapter 6, but you need not go back and read
that subsection. The presentation of for-each loops here is complete.
For example, the following code ends with a for-each loop that outputs all the
elements in the
ArrayList
named
mylist
:
for-each loop
ArrayList<String> myList =
new
ArrayList<String>(20);
<
Some code to fill
myList
>
for
(String element : myList)
System.out.println(element);
You can read the line beginning with
for
as “for each
element
in
myList
, do the
following.” Note that the variable,
element
, has the same type as the elements in the
ArrayList
. The variable (in this case,
element
), must be declared in the for-each loop
as we have done. If you attempt to declare
element
before the for-each loop, you will
get a compiler error message.
The general syntax for a for-each loop statement is
for
(
Base_Type
Variable
:
Collection_Object
)
Statement
Be sure to notice that you use a colon (not a semicolon) after the
Variable
. You may
use any legal variable name for the
Variable
; you do not have to use
element
. The only