Java Reference
In-Depth Information
for(int i = 0 ; i < filmCast.size() ; ++i) {
System.out.println(filmCast.get(i));
}
The collection-based for loop is the simplest way of all for listing the contents of the vector:
for(Person person : filmCast) {
System.out.println(person);
}
To output the space remaining in the vector, you calculate the difference between the capacity and the
size:
System.out.println("\nThe vector currently has room for "
+ (filmCast.capacity() - count) + " more people.");
This is interesting but irrelevant because the vector accommodates as many stars as you care to enter.
The static readPerson() method is a convenient way of managing the input. The input source is the
static class member defined by the following statement:
static BufferedReader keyboard = new BufferedReader(
new
InputStreamReader(System.in));
The keyboard object is System.in wrapped in an InputStreamReader object that is wrapped in a
BufferedReader object. The InputStreamReader object provides conversion of the input from the
byte stream System.in to characters. The BufferedReader object buffers the data read from the In-
putStreamReader . Because the input consists of a series of strings entered one to a line, the readLine()
method does everything you need. The calls to readLine() is in a try block because it can throw an
IOException . The call to the trim() method for the String object returned by the readLine() method
removes leading or trailing blanks.
Sorting a Collection
The output from the last example appears in the sequence in which you enter it. If you want to arrange them
in alphabetical order you could write your own method to sort Person objects in the filmCast object, but it
is a lot less trouble to take advantage of another feature of the java.util package, the Collections class
— not to be confused with the Collection<> interface. The Collections class defines a variety of handy
static utility methods that you can apply to collections, and one of them happens to be a sort() method.
The sort() method only sorts lists — that is, collections that implement the List<> interface. Obviously
there has to be some way for the sort() method to determine the order of objects from the list that it is
sorting — in your case, Person objects. The most suitable way to do this is to implement the Comparable<>
interface in the Person class. As you know, the Comparable<> interface declares only one method, com-
pareTo() . You saw this method in the previous chapter so you know it returns -1, 0, or +1 depending on
whether the current object is less than, equal to, or greater than the argument. If the Comparable<> interface
is implemented for the type of object stored in a collection, you can just pass the collection object as an
argument to the sort() method. The collection is sorted in place so there is no return value.
Search WWH ::




Custom Search