Java Reference
In-Depth Information
Display 14.1
Some Methods in the Class
ArrayList
(part 3 of 3)
public int
indexOf(Object target)
Returns the index of the first element that is equal to
target
. Uses the method
equals
of the
object
target
to test for equality. Returns
—1
if
target
is not found.
public int
lastIndexOf(Object target)
Returns the index of the last element that is equal to
target
. Uses the method
equals
of the
object
target
to test for equality. Returns -
1
if
target
is not found.
MEMORY MANAGEMENT (SIZE AND CAPACITY)
public boolean
isEmpty()
Returns
true
if the calling
ArrayList
is empty (that is, has size
0
); otherwise, returns
false
.
public int
size()
Returns the number of elements in the calling
ArrayList
.
public void
ensureCapacity(
int
newCapacity)
Increases the capacity of the calling
ArrayList
, if necessary, in order to ensure that
the
ArrayList
can hold at least
newCapacity
elements. Using
ensureCapacity
can
sometimes increase efficiency, but its use is not needed for any other reason.
public void
trimToSize()
Trims the capacity of the calling
ArrayList
to the
ArrayList
's current size. This method is
used to save storage space.
MAKE A COPY
public
Object[] toArray()
Returns an array containing all the elements on the list. Preserves the order of the elements.
public
Type
[] toArray(
Type
[] a)
Returns an array containing all the elements on the list. Preserves the order of the elements.
Type
can
be any class types. If the list will fit in
a
, the elements are copied to
a
and
a
is returned. Any elements
of
a
not needed for list elements are set to
null
. If the list will not fit in
a
, a new array is created.
(As we will discuss in Section 14.2, the correct Java syntax for this method heading is
public
<Type> Type[] toArray( Type[] a)
However, at this point we have not yet explained this kind of type parameter syntax.)
public
Object clone()
Returns a shallow copy of the calling
ArrayList
.
Warning
: The clone is not an independent copy.
Subsequent changes to the clone may affect the calling object and vice versa. (See Chapter 5 for a
discussion of shallow copy.)
EQUALITY
public boolean
equals(Object other)
If
other
is another
ArrayList
(of any base type), then
equals
returns
true
if, and only if,
both
ArrayList
s are of the same size and contain the same list of elements in the same order.
(In fact, if
other
is any kind of
list
, then
equals
returns
true
if, and only if, both the calling
ArrayList
and
other
are of the same size and contain the same list of elements in the same
order. Lists are discussed in Chapter 16.)