Java Reference
In-Depth Information
second call on
remove
is performed, Java removes
"Phish"
from the list because it
is the value that is in position 1 at that point in time.
If you want to find out the number of elements in an
ArrayList
, you can call its
size
method. If you want to obtain an individual item from the list, you can call its
get
method, passing it a specific index. For example, the following loop would add
up the lengths of the
String
s in an
ArrayList<String>
:
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
sum += s.length();
}
System.out.println("Total of lengths = " + sum);
This loop looks similar to the kind of loop you would use to access the various
elements of an array, but instead of asking for
list.length
as you would for an
array, you ask for
list.size()
, and instead of asking for
list[i]
as you would
with an array, you ask for
list.get(i)
.
Calling
add
and
remove
can be expensive in terms of time because the computer
has to shift the values around. If all you want to do is to replace a value, you can use
a method called
set
, which takes an index and a value and replaces the value at the
given index with the given value, without doing any shifting. For example, you could
replace the value at the front of the sample list by writing the following line of code:
list.set(0, "The Violent Femmes");
As noted earlier, when you construct an
ArrayList
it will initially be empty.
After you have added values to a list, you can remove them one at a time. But what if
you want to remove all of the values from the list? In that case, you can call the
clear
method of the
ArrayList
.
Table 10.1 summarizes the
ArrayList
operations introduced in this section. A
more complete list can be found in the online Java documentation.
Once you have built up an
ArrayList
, you might be interested in searching for a
specific value in the list. The
ArrayList
class provides several mechanisms for
doing so. If you just want to know whether or not something is in the list, you can
call the
contains
method, which returns a Boolean value. For example, suppose you
have an input file of names that has some duplicates, and you want to get rid of the
duplicates. The file might look like this:
Maria Derek Erica
Livia Jack Anita
Kendall Maria Livia Derek
Jamie Jack
Erica
Search WWH ::
Custom Search