Java Reference
In-Depth Information
Display 14.1
Some Methods in the Class
ArrayList
(part 2 of 4)
public
ArrayList<
Base_Type
>()
Creates an empty
ArrayList
with the specified
Base_Type
and an initial capacity of
10
.
ARRAYLIKE METHODS
public
Base_Type
set(
int
index,
Base_Type
newElement)
Sets the element at the specified
index
to
newElement
. Returns the element previously at that posi-
tion, but the method is often used as if it were a
void
method. If you draw an analogy between the
ArrayList
and an array
a
, this statement is analogous to setting
a[index]
to the value
newElement
.
The
index
must be a value greater than or equal to
0
and less than the current size of the
ArrayList
.
Throws an
IndexOutOfBoundsException
if the
index
is not in this range.
public
Base_Type
get(
int
index)
Returns the element at the specified index. This statement is analogous to returning
a[index]
for an
array
a
. The
index
must be a value greater than or equal to
0
and less than the current size of the
ArrayList
. Throws
IndexOutOfBoundsException
if the
index
is not in this range.
METHODS TO ADD ELEMENTS
public boolean
add(
Base_Type
newElement)
Adds the specified element to the end of the calling
ArrayList
and increases the
ArrayList
's size by
one. The capacity of the
ArrayList
is increased if that is required. Returns
true
if the add was success-
ful. (The return type is
boolean
, but the method is typically used as if it were a
void
method.)
public
void
add(
int
index,
Base_Type
newElement)
Inserts
newElement
as an element in the calling
ArrayList
at the specified index. Each element in
the
ArrayList
with an index greater or equal to
index
is shifted upward to have an index that is one
greater than the value it had previously. The
index
must be a value greater than or equal to
0
and less
than or equal to the current size of the
ArrayList
. Throws
IndexOutOfBoundsException
if the index
is not in this range. Note that you can use this method to add an element after the last element. The
capacity of the
ArrayList
is increased if that is required.
METHODS TO REMOVE ELEMENTS
public
Base_Type
remove(
int
index)
Deletes and returns the element at the specified index. Each element in the
ArrayList
with an
index greater than
index
is decreased to have an index that is one less than the value it had previ-
ously. The
index
must be a value greater than or equal to
0
and less than the current size of the
ArrayList
. Throws
IndexOutOfBoundsException
if the
index
is not in this range. Often used as if
it were a
void
method.
protected void
removeRange(
int
fromIndex,
int
toIndex)
Deletes all the element with indices
i
such that
fromIndex
≤
i
<
toIndex
. Element with indices
greater than or equal to
toIndex
are decreased appropriately.