Java Reference
In-Depth Information
Chapter 7 explored the following code for printing the contents of an array of integers:
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("]");
}
}
The code involves a fencepost loop because we use commas to separate values. If
there are n numbers, they will be separated by n
1 commas. The code uses the
classic fencepost solution of printing the first value before the loop. The if/else is
used because there is a special case if the array is empty. This code can be fairly easily
adapted to your ArrayIntList class. You have to convert the static method into an
instance method. As a result, instead of having a parameter called list , you refer to
the field called elementData . You also want to modify the code so that it uses the
size of the list rather than the length of the array:
public void print() {
if (size == 0) {
System.out.println("[]");
} else {
System.out.print("[" + elementData[0]);
for (int i = 1; i < size; i++) {
System.out.print(", " + elementData[i]);
}
System.out.println("]");
}
}
But you don't want a method to print the list. If you want to make a truly useful
class, you should provide flexible mechanisms that will work in a wide variety of
situations. A better solution is to return a string representation of the list rather than
printing it. As we saw in Chapter 8, Java has a standard name for such a method:
toString . So you should rewrite the preceding method to construct and return a
string representation of the list:
public String toString() {
if (size == 0) {
Search WWH ::




Custom Search