Java Reference
In-Depth Information
Arrays.toString . The printing statements just before and just after the loop have
been modified to include square brackets, and a special case has been included for
empty arrays:
public static void print(int[] list) {
if (list.length == 0) {
System.out.println("[]");
} else {
System.out.print("[" + list[0]);
for (int i = 1; i < list.length; i++) {
System.out.print(", " + list[i]);
}
System.out.println("]");
}
}
Searching and Replacing
Often you'll want to search for a specific value in an array. For example, you might
want to count how many times a particular value appears in an array. Suppose you
have an array of int values like the following:
[0]
[1]
[2]
[3]
[4]
[5]
[6]
list
8
7
19
82
8
7
8
Counting occurrences is the simplest search task, because you always examine
each value in the array and you don't need to change the contents of the array. You
can accomplish this task with a for-each loop that keeps a count of the number of
occurrences of the value for which you're searching:
public static int count(int[] list, int target) {
int count = 0;
for (int n : list) {
if (n == target) {
count++;
}
}
return count;
}
You can use this method in the following call to figure out how many 8s are in the
list:
int number = count(list, 8);
 
Search WWH ::




Custom Search