Created
March 21, 2017 14:01
-
-
Save nicoulaj/d923eedcba99d4b0e529bfaf8c31c0f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Check comparator respects its contract against a given collection. | |
* | |
* @param elements | |
* collection | |
* @param comparator | |
* comparator | |
*/ | |
public static <T> void checkComparatorContract(Collection<T> elements, Comparator<? super T> comparator) { | |
@SuppressWarnings("unchecked") | |
final T[] array = elements.toArray((T[]) new Object[elements.size()]); | |
elements.parallelStream().forEach(x -> { | |
for (T y : array) { | |
// The implementor must ensure that sgn(compare(x, y)) == | |
// -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) | |
// must throw an exception if and only if compare(y, x) throws an | |
// exception.) | |
final int xy = comparator.compare(x, y); | |
final int yx = comparator.compare(y, x); | |
if (xy * yx > 0) | |
throw new IllegalStateException("Non symetric signum on " + LINE_SEPARATOR + x + ", " | |
+ LINE_SEPARATOR + y + LINE_SEPARATOR + "(" + xy + " and " + yx | |
+ ")"); | |
if (xy >= 0) | |
for (T z : array) { | |
final int xz = comparator.compare(x, z); | |
final int yz = comparator.compare(y, z); | |
// The implementor must also ensure that the relation is transitive: | |
// ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0. | |
if (xy > 0 && yz > 0 && xz < 0) | |
throw new IllegalStateException("Comparator says: " + LINE_SEPARATOR + x + " > " + y | |
+ LINE_SEPARATOR + y + " > " + z + LINE_SEPARATOR + x | |
+ " < " + z + LINE_SEPARATOR); | |
// Finally, the implementor must ensure that compare(x, y)==0 implies | |
// that sgn(compare(x, z))==sgn(compare(y, z)) for all z. | |
if (xy == 0 && xz * yz < 0) | |
throw new IllegalStateException("Wrong signum on " + x + ", " + y + ", " + z); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment