Java Reference
In-Depth Information
The
indexOf
method takes a particular value and returns the index of the first
occurrence of the value in the list. If it doesn't find the value, it returns
-1
. So, you
could write a
replace
method as follows:
public static void replace(ArrayList<String> list,
String target, String replacement) {
int index = list.indexOf(target);
if (index >= 0) {
list.set(index, replacement);
}
}
Notice that the return type of this method is
void
, even though it changes the con-
tents of an
ArrayList
object. Some novices think that you have to return the
changed
ArrayList
, but the method doesn't actually create a new
ArrayList
; it
merely changes the contents of the list. As you've seen with arrays and other objects,
a parameter is all you need to be able to change the current state of an object because
objects involve reference semantics in which the method is passed a reference to the
object.
You can test the method with the following code:
ArrayList<String> list = new ArrayList<String>();
list.add("to");
list.add("be");
list.add("or");
list.add("not");
list.add("to");
list.add("be");
System.out.println("initial list = " + list);
replace(list, "be", "beep");
System.out.println("final list = " + list);
This code produces the following output:
initial list = [to, be, or, not, to, be]
final list = [to, beep, or, not, to, be]
There is also a variation of
indexOf
known as
lastIndexOf
. As its name
implies, this method returns the index of the last occurrence of a value. There
are many situations where you might be more interested in the last occurrence
rather than the first occurrence. For example, if a bank finds a broken automated
teller machine, it might want to find out the name and account number of the last
customer to use that machine. Table 10.2 summarizes the
ArrayList
searching
methods.
Search WWH ::
Custom Search