Java Reference
In-Depth Information
TreeSet of players, ordered by our comparator. We will then iterate over that set, and print
out the players in the order given by the iterator. The whole method looks like:
public static void FormatBattingAvg(Team toFormat){
TreeSet<Player> battingSort =
new TreeSet<Player>(new BattingComparator());
float avg = 0.0f;
for (Player p : battingSort){
System.out.print(p.getName() + "\t");
if (p.hasRole(Roles.Batter)){
try {
avg = p.asBatter().getAverage();
} catch (NotEnoughAtBatsException e) {
avg = 0.0f;
avg = 0.0f;
We start by creating a TreeSet object, battingSort , using our BattingComparator object
as the ordering function. We then add all of the members of the supplied Team in a single call.
This is another instance of the collections library saving us from having to write code. Al-
though it would be easy for us to iterate through the players on a team and add them one by
one, all of the collections allow this kind of batch initialization from another collection, mean-
ing we have less code to write, test, and optimize. We then print out the players in the order
induced by the comparator, printing out the average of those who either aren't batters or have
no batting average as 0.
Unfortunately, this will print out the players in ascending order of batting average, which is
probably not what we want. We could change our comparator to make it reverse the usual
notion of greater-than, so the players with the higher average are printed out first. But doing
such a counterintuitive thing is also a way of introducing bugs (“Did I mean really greater, or
reverse greater?”), so we will take a different tack. We will still order in the set using the ob-
vious comparator, but we will print out our set in reverse order. The TreeSet class lets us get
the last member of the set (in our induced order), and since it is a set, we can remove elements
at will. So to print in reverse order, we would need something like:
Search WWH ::

Custom Search