Details
-
Bug
-
Status: Closed
-
Major
-
Resolution: Fixed
-
1.1-rc-2
-
None
Description
Example Code:
class Foo implements Comparable { private int key public Foo(int k) { key = k } public int compareTo(Object rhs) { return key - rhs.key } public String toString() { return "foo: " + key } } class Bar extends Foo { public Bar(int x) { super(x) } } def listOfFoo = [ new Foo(7), new Bar(6), new Foo(5), new Bar(4) ] listOfFoo.sort() println(listOfFoo)
Output of this script might be, for example (one cannot really tell, since the result is definitely VM/environment dependent):
groovy compareex.groovy
[foo: 6, foo: 5, foo: 7, foo: 4]
Reason: DefaultGroovyMethods.NumberAwareComparator: The default comparator used by the "sort()" implementation has a serious bug. Thanks to the test "o1.getClass() == o2.getClass()", the "compareTo" of class Foo won't be invoked whenever comparing a Foo with a Bar. This is – at best – counter-intuitive. You can work around this by providing a trivial comparator closure
{ x, y -> x.compareTo(y) }.
This bug exists at least since version 1.0 (though the comparator class had a different name then)
Speaking about the NumberAwareComparator: is the "equals" method ever called? I hope it's not, since it looks suspiciously like an infinite recursion to me.