Created
February 21, 2012 17:54
-
-
Save andrelashley/1877716 to your computer and use it in GitHub Desktop.
Java Notes - February 21: Alternate forms of comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- 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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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