为什么此比较输出是输出true
?
import scala.collection.immutable.ListSet
Set(1) == ListSet(1) // Expect false
//Output
res0: Boolean = true
从更一般的意义上讲,实际上是如何进行比较的?
由于继承链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
}
本质上,它检查另一个对象是否也是GenSet
,如果是,则尝试执行一些快速失败检查(例如比较size
和调用canEqual
),并且如果大小相等,则检查该集合是否是另一个集合的子集。 ,大概是通过检查每个元素。
因此,用于在运行时表示集合的确切类无关紧要,重要的是被比较的对象也是aGenSet
且具有相同的元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句