Last active
August 29, 2015 14:00
-
-
Save akisute/11284077 to your computer and use it in GitHub Desktop.
This is how I implement Comparator
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 static class MyComparator implements Comparator<MyClass> { | |
@Override | |
public int compare(MyClass obj1, MyClass obj2) { | |
int value1 = obj1.getValue(); | |
int value2 = obj2.getValue(); | |
// Dumb way | |
if (value1 == value2) { | |
return 0; | |
} else if (value1 > value2) { | |
return 1; | |
} else { | |
return -1; | |
} | |
// LOOKS-LIKE-Cool way (but not safe) | |
// Suffers from overflow when value2 is Integer.MAX_VALUE | |
return value1 - value2; | |
// Best way | |
return Integer.compare(value1, value2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment