Java Reference
In-Depth Information
You can use this method in the following call to find the first occurrence of the
value 7 in the list:
int position = indexOf(list, 7);
This call would set position to 1 for the sample array, because the first occur-
rence of 7 is at index 1. There is another occurrence of 7 later in the array, at index 5,
but this code terminates as soon as it finds the first match.
If you instead made the call
int position = indexOf(list, 42);
position would be set to -1 because there are no occurrences of 42 in the list.
As a final variation, consider the problem of replacing all the occurrences of a value
with some new value. This is similar to the counting task. You'll want to traverse the
array looking for a particular value and replace the value with something new when
you find it. You can't accomplish that task with a for-each loop, because changing the
loop variable has no effect on the array. Instead, use a standard traversing loop:
public static void replaceAll(int[] list, int target, int replacement) {
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
list[i] = replacement;
}
}
}
Notice that even though the method is changing the contents of the array, you
don't need to return it in order to have that change take place.
As we noted at the beginning of this section, these examples involve an array of
integers, and you would have to change the type if you were to manipulate an array
of a different type (for example, changing int[] to double[] if you had an array of
double values). But the change isn't quite so simple if you have an array of objects,
such as String s. In order to compare String values, you must make a call on the
equals method rather than using a simple == comparison. Here is a modified version
of the replaceAll method that would be appropriate for an array of String s:
public static void replaceAll(String[] list, String target,
String replacement) {
for (int i = 0; i < list.length; i++) {
if (list[i].equals(target)) {
list[i] = replacement;
}
}
}
 
Search WWH ::




Custom Search