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

Collection.unique() method might remove not duplicate items

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 1.8-beta-1
    • groovy-jdk
    • None
    • Windows XP, JDK 1.6.0_19, GROOVY 1.7.0

    Description

      list=[[3035, 26972], [2795, 34412]]
      list.unique()
      println list

      Result: [[3035, 26972]]

      list=[[3035, 26972], [2795, 34412]]
      list.unique

      {it}

      println list

      Result: [[3035, 26972]]

      Because the unique method use NumberAwareComparator<T> to compare elements in the collection, and NumberAwareComparator<T> will use object's hashCode to compare two object when the object doesn't have a compareTo method, then the two list [3035, 26972], [2795, 34412] are considered to be duplicate(because they have the same hashCode).

      Will it be better to use equals method to decide whether two elements are duplicate?
      As the document say:
      "A convenience method for making a collection unique using a Closure to determine duplicate (equal) items. If the closure takes a single parameter, the argument passed will be each element, and the closure should return a value used for comparison (either using

      {@link Comparable#compareTo(Object)}

      or

      {@link Object#equals(Object)}

      ). If the closure takes two parameters, two items from the collection will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique)."

      Attachments

        1. groovy4257_SetUnique.patch
          3 kB
          Paul King

        Activity

          People

            paulk Paul King
            fangyixun Yixun Fang
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: