Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2321

Sort fails on heterogenous collections

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.1-rc-2
    • 1.1-rc-3
    • groovy-jdk
    • 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.

      Attachments

        Activity

          People

            paulk Paul King
            dirkesser Dirk Eßer
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: