Skip to content

Instantly share code, notes, and snippets.

@akisute
Last active August 29, 2015 14:00
Show Gist options
  • Save akisute/11284077 to your computer and use it in GitHub Desktop.
Save akisute/11284077 to your computer and use it in GitHub Desktop.
This is how I implement Comparator
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