Skip to content

TreeSet equality gives unexpected result based on compare only #10741

Open
@dariodariodario

Description

@dariodariodario

I stumbled upon this and it left me quite surprised:

import org.scalatest.FlatSpec
import scala.collection.immutable.TreeSet

class TreeSetSpec extends FlatSpec{

  case class A(val x : Int, val y : String) extends Ordered[A]{
    override def compare(that: A): Int = this.x.compareTo(that.x)
  }

  "TreeSet with different elements" should "be different" in {

    val a1 = A(1, "Hello")
    val a2 = A(1, "bye")

    val t1 = TreeSet[A](a1)
    val t2 = TreeSet[A](a2)

    assert(t1 != t2)
  }
}

this test won't pass and the two treesets will evaluate as equal. My understanding was that the compare of the ordered trait was only for sorting the Set, while element equality should rely on equals of the type parameter

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions