Java Reference
In-Depth Information
break; // We are done...
filmCast.add(aPerson); // Otherwise, add to the cast
}
int count = filmCast.size();
System.out.println("You added "+count +
(count == 1 ? " person": " people")+ " to the cast.\n");
filmCast.sort(); // Sort the cast
// Show who is in the cast using an iterator
Iterator thisLot = filmCast.iterator(); // Obtain an iterator
while(thisLot.hasNext()) // Output all elements
System.out.println( thisLot.next() );
}
If you run the example with these changes, the cast will be in alphabetical order in the output. Here's
what I got:
Enter first name or ! to end:
Roy
Enter surname:
Rogers
Enter first name or ! to end:
Mae
Enter surname:
West
Enter first name or ! to end:
Charles
Enter surname:
Chaplin
Enter first name or ! to end:
!
You added 3 people to the cast.
Charles Chaplin
Roy Rogers
Mae West
How It Works
The sort() method for the Crowd object calls the sort() method defined in the Collections
class, and this sorts the objects in the people vector in place. Like shelling peas!
Search WWH ::




Custom Search