CHAPTER 4 ■ OPERATORS
characters.add(drWatson);
// sort by the natural values (uses compareTo())
Collections.sort(characters);
for (int i = 0; i < characters.size(); i++) {
Person person = characters.get(i);
System.out.println(person.firstName + " "
- person.lastName + " likes " + person.favoriteBook);
}
System.out.println();
System.out.println("Sorting by favorite book");
// sort by book (uses the Comparator)
Collections.sort(characters, new BookComparator());
for (int i = 0; i < characters.size(); i++) {
Person person = characters.get(i);
System.out.println(person.firstName + " " - person.lastName + " likes " + person.favoriteBook);
}
}
}
And Listing 4-34 shows the output from our test class.
Listing 4-34. CompareTest output
false
true
Sorting by name
Sherlock Holmes likes The Sign of the Four
Sam Spade likes The Maltese Falcon
John Watson likes A Study in Scarlet
John Watson likes A Study in Scarlet
Sorting by favorite book
John Watson likes A Study in Scarlet
John Watson likes A Study in Scarlet
Sam Spade likes The Maltese Falcon
Sherlock Holmes likes The Sign of the Four
Summary
In this chapter, we learned:
- Java has a large number of operators.
- Java's operators have precedence (that is, some operators are processed before
other operators). - Java has some seemingly odd operators (such as the bitwise operators) but that
they all have their uses.