Skip to content

Instantly share code, notes, and snippets.

@andrelashley
Created February 21, 2012 17:54
Show Gist options
  • Save andrelashley/1877716 to your computer and use it in GitHub Desktop.
Save andrelashley/1877716 to your computer and use it in GitHub Desktop.
Java Notes - February 21: Alternate forms of comparison
public class AlternateHockeyPlayerComparer{
int compare(HockeyPlayer a, HockeyPlayer b){
String aLastName = a.getLastName();
String bLastName = b.getLastName();
int difference = a.lastName.compareTo(b.lastName);
if(difference != 0){
return difference;
}
String aFirstName = a.getLastName();
String bFirstName = b.getLastName();
difference = a.firstName.compareTo(b.firstName)
return difference;
}
}
- Sorting does Collections.min() repeatedly, comparing pairs of objects at a time
- Only one sort routine, one compareTo method per class
- A compare yourself to B, and tell me which one is bigger?
Alternate forms of comparison
- the long version
- the really short version
- To solve the sorting problem, add a layer to it
- add a separate object whose job it is to compare two objects
- Java already has a built-in object for sorting (comparator interface)
- You can use a comparator object as an inner class
- Anonymous Inner Class, a class within a class without a name
- Anonymous inner classes tend to be more explicit, but slightly difficult to read
AlternateHockeyPlayerComparer andre = new AlternateHockeyPlayerComparer();
Collections.sort(aTeam, andre); // takes a list and a comparator object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment