Best possible "generic" implementation of Comparator?
-
01-07-2022 - |
Question
We recently had some troubles migrating from Java 6 to 7 because we have tonns of Comparator implemented in a way they not fullfill the Comparable contract and throw a Exception using the new Timsort algorithms.
Edit: Input from User Marco Forberg and class signature
I now found a Comparator many of the others are extending from, the compare method looked like this:
@Override
public int compare(final T o1, final T o2) {
return 0;
}
And i changed it to this in the hope i cover most of the cases:
@Override
public int compare(final T o1, final T o2) {
//Case: XOR check for either s1 or s2 being null
if(o1 == null ^ o2 == null){
return (o1 == null) ? -1 : 1;
}
//Case: both are null
if(o1 == o2){
return 0;
}
//Case: Its Comparable!
if(o1 instanceof Comparable && o2 instanceof Comparable){
Comparable c1 = (Comparable) o1;
Comparable c2 = (Comparable) o2;
return ObjectUtils.compare(c1, c2);
}
//Case: We don't know (ran for years this way)
return 0;
}
The class signature looks like this:
public class MyComparator<T> implements Comparator<T> {
While ObjectUtils
is from the Apache Commons 3 and provides a null-safe compare method (I know the time i call this none of the both objects can be null because of the previous checks and i could use c1.compare(c2) as well)
Did this improve the behavior of the "Base"-Comparator? (which i assume) and i am right that this would basically cover the Comparable contract since the value 0 is now returned for non-comparable Objects?
No correct solution