Java Reference
In-Depth Information
er than the other (and the other less than the one). For our case of a comparator that deals
with batting averages, this means that we need to add some code that will order players who
have the same batting average. And since we want to order all of the players that get put in-
to a set, we will also want our comparator to deal with players who have no batting average,
either because they don't have enough at-bats or because they aren't batters at all (those pesky
American League pitchers).
So our comparator will first look to see whether the Player has the role of a Batter . If not, or
if the player does not have enough at-bats to have a valid average, then we will just set their
batting average to zero. We will also break ties in the batting average by using the player's
identifier. It would be more user-friendly to break ties using something that makes sense to the
user, like the player's name, but the name is not guaranteed to be unique, so there is a small
chance that two players with the same batting average could also have the same name. This
might not be very likely, but we will be paranoid. Since the Id is guaranteed to be unique, it's
a great way to make sure that the ordering induced by our comparator is a full ordering. We
will also use the Id to determine equality: two Player objects will be equal if they have the
same Id . Having made these decisions, the comparator looks like:
package org.oreilly.javaGoodParts.examples.impl;
import java.util.Comparator;
import org.oreilly.javaGoodParts.examples.statistics.NotEnoughAtBatsException;
import org.oreilly.javaGoodParts.examples.statistics.Player;
/**
* A comparator that will rank players depending on
* their batting average. If both players have a
* batting average, the one with the higher average
* is compared as greater than the other. Players with
* insufficient at bats or who don't bat at all are
* dealt with as if their batting average is 0. If two
* players have the same batting average, they will
* be compared based on their player ids, which are
* guaranteed to be unique.
*
* This comparison will give a well-ordering to any
* collection of players, based on their batting average.
* Ties are broken by using the Id field of the player, which
* is also used to determine equality.
*/
public class BattingComparator implements Comparator<Player>{
Search WWH ::




Custom Search