Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

462 Part II: The Java Library


System.out.println();

// Now, sum the values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;

System.out.println("Sum of values: " + sum);
}
}

The output from the program is shown here:

Original contents of vals: 1 2 3 4 5
Sum of values: 15

As you can see, theforloop is substantially shorter and simpler to use than the iterator-
based approach. However, it can only be used to cycle through a collection in the forward
direction, and you can’t modify the contents of the collection.

Storing User-Defined Classes in Collections


For the sake of simplicity, the foregoing examples have stored built-in objects, such asString
orInteger, in a collection. Of course, collections are not limited to the storage of built-in
objects. Quite the contrary. The power of collections is that they can store any type of object,
including objects of classes that you create. For example, consider the following example that
uses aLinkedListto store mailing addresses:

// A simple mailing list example.
import java.util.*;

class Address {
private String name;
private String street;
private String city;
private String state;
private String code;

Address(String n, String s, String c,
String st, String cd) {
name = n;
street = s;
city = c;
state = st;
code = cd;
}

public String toString() {
return name + "\n" + street + "\n" +
city + " " + state + " " + code;
}
}
Free download pdf