Aar*_*_ab 4 collections comparison scala
为什么这个比较的输出会输出true?
import scala.collection.immutable.ListSet
Set(1) == ListSet(1) // Expect false
//Output
res0: Boolean = true
Run Code Online (Sandbox Code Playgroud)
从更一般的意义上讲,实际比较是如何进行的?
由于继承链Set <: GenSet <: GenSetLike有点冗长,可能不会立即明显在哪里查找代码equals,所以我想也许我在这里引用它:
/** Compares this set with another object for equality.
*
* '''Note:''' This operation contains an unchecked cast: if `that`
* is a set, it will assume with an unchecked cast
* that it has the same element type as this set.
* Any subsequent ClassCastException is treated as a `false` result.
* @param that the other object
* @return `true` if `that` is a set which contains the same elements
* as this set.
*/
override def equals(that: Any): Boolean = that match {
case that: GenSet[_] =>
(this eq that) ||
(that canEqual this) &&
(this.size == that.size) &&
(try this subsetOf that.asInstanceOf[GenSet[A]]
catch { case ex: ClassCastException => false })
case _ =>
false
}
Run Code Online (Sandbox Code Playgroud)
本质上,它检查另一个对象是否也是a GenSet,如果是,它会尝试执行一些快速失败检查(比如比较size和调用canEqual),如果大小相等,它会检查这个集合是否是另一个集合的子集,大概是通过检查每个元素.
因此,用于在运行时表示集合的确切类是无关紧要的,重要的是比较对象也是a GenSet并且具有相同的元素.