I'm using com.google.common.collect.ComparatorChain
to implement a custom comparator for different objects.
Now, the following tests fails, but why?
@Test
public void chainTest() {
ComparisonChain comparator = ComparisonChain.start()
.compare("a", "a");
assertTrue(comparator.result() == 0);
comparator.compare("a", "b");
assertTrue(comparator.result() != 0); //fails with AssertionError
}
Afaik the 2nd result should actually be != 0
as a != b
?
I could of course reassign the comparator like:
comparator = comparator.compare("a", "b");
But that would discard any results that were optained before the reassignment.
You're ignoring the return value of comparator.compare("a", "b")
. Calling compare()
doesn't change the state of the existing comparison - it returns a comparison with the right state (which may or may not be the same - as long as the result of the comparison is 0, the state will be "active").
Change your code to use:
comparator = comparator.compare("a", "b");
and it should work.
The idea is that you just keep passing comparisons to the chain, and it will ignore them as soon as it knows the overall result (i.e. when one of them is non-zero). For example:
import com.google.common.collect.ComparisonChain;
public class Test {
public static void main(String[] args) {
int result = ComparisonChain.start()
.compare("a", "b") // Chain terminates here
.compare("a", "a") // Irrelevant
.result();
System.out.println(result); // < 0 (e.g. -1)
}
}
See more on this question at Stackoverflow