Java Reference
In-Depth Information
...
<statement>;
}
In this section we will explore some common array algorithms that can be imple-
mented with these patterns. Of course, not all array operations can be implemented
this way—the section ends with an example that requires a modified version of the
standard code.
We will implement each operation as a method. Java does not allow you to write
generic array code, so we have to pick a specific type. We'll assume that you are
operating on an array of int values. If you are writing a program to manipulate a dif-
ferent kind of array, you'll have to modify the code for the type you are using (e.g.,
changing int[] to double[] if you are manipulating an array of double values).
Printing an Array
Suppose you have an array of int values like the following:
[0]
[1]
[2]
[3]
[4]
[5]
[6]
list
17
-3
42
8
12
2
103
How would you go about printing the values in the array? For other types of data,
you can use a println statement:
System.out.println(list);
Unfortunately, as mentioned in the Arrays class section of this chapter, with an
array the println statement produces strange output like the following:
[I@6caf43
This is not helpful output, and it tells us nothing about the contents of the array.
We saw that Java provides a solution to this problem in the form of a method called
Arrays.toString that converts the array into a convenient text form. You can
rewrite the println as follows to include a call on Arrays.toString :
System.out.println(Arrays.toString(list));
This line of code produces the following output:
[17, -3, 42, 8, 12, 2, 103]
This is a reasonable way to show the contents of the array, and in many situations
it will be sufficient. However, for situations in which you want something different,
you can write your own method.
 
Search WWH ::




Custom Search