2

有人可以帮我理解以下内容吗?如果我创建元素的树形图,scala 似乎决定我的比较方法也确定元素的相等性,因此根据“比较”方法删除相同的元素。我没想到这一点,因为如果我没有覆盖它,仍然应该根据对象相等来定义相等?

import scala.collection.mutable._

class A(val num: Int) extends Ordered[A] {
    def compare (that: A) = {
        this.num - that.num
    }
    override def toString() = {
      num+""
    }
}

object A {
    def main(args: Array[String]) = {

        val mySet = new TreeSet[A]()
        mySet += new A(3)
        mySet += new A(2)
        mySet += new A(1)
        mySet += new A(3)
        mySet += new A(2)
        mySet += new A(1)

        mySet.foreach(println)
    }
}

1
2
3

不是预期的(我)

1
1
2
2
3
3
4

3 回答 3

5

Your intuitive assumption is understandable, but in general TreeSet implementations often rely on comparison methods rather than equality, since the compare operations returns 0 only if the two objects are equal; for Scala, it says so in the doc (compare method).

In Java's TreeSet this is even mentioned explicitly.

In Scala, this is not as obvious from the docs, but if you look at the source code, you'll see that the Scala TreeSet relies on the RedBlackTree implementation internally, which, in its lookup method, uses the result of compare for testing equality exclusively.

And that's perfectly valid, due to Ordering.compare's contract, as noted in the first paragraph - i.e. if you get 0, the two objects are equal by definition.

于 2013-11-08T15:08:37.470 回答
2

来自文档:

“ Ordered[A] 实例的 equals 方法必须与 compare 方法保持一致,这一点很重要。但是,由于类型擦除语义固有的限制,没有合理的方法为实例提供相等的默认实现已订购[A]"

所以你应该提供你自己的 hashcode 和 equals 方法。

于 2013-11-08T15:12:13.820 回答
1

据我记得, SortedSet 不允许重复,因此在您的代码中,树的最后插入被忽略

于 2013-11-08T15:12:55.400 回答