Scala-集合比较-为什么Set(1)== ListSet(1)?

Aaron_ab

为什么此比较输出是输出true

import scala.collection.immutable.ListSet

Set(1) == ListSet(1) // Expect false

//Output
res0: Boolean = true 

从更一般的意义上讲,实际上是如何进行比较的?

安德烈(Andrey Tyukin)

由于继承链Set <: GenSet <: GenSetLike有点长,因此在哪里寻找的代码可能并不立即显而易见equals,所以我想也许我在这里引用它:

GenSetLike.scala

  /** 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么PowerShell比较运算符不枚举大小为1的集合?

如何在集合类型之间转换-在Scala中设置为ListSet

从1元素Scala集合中获取元素

为什么Scala仅对Function1实现andThen函数

什么是集合的非扁平化Scala向量:(1至2).flatMap((1至3).toSet.subsets(_))?

为什么n + 1选择模式比较慢?

Scala:为什么foo(1,2)和foo((1,2))相同?

在Scala中,为什么Array(“ 1”)++“ -3”输出Array [Any] = Array(1,-,3)?

为什么Scala中的'def aPlusOne = a + 1'和`val aPlusOne =()=> a + 1`不同?

为什么默认情况下,scala的集合不是“视图”?

为什么Scala哈希图比较慢?

Scala中的基础集合类是什么?

为什么“1 Math.pow 2”在 Scala 中不起作用?

Scala:为什么classOf [Int] .cast(1)抛出java.lang.ClassCastException?

JavaScript比较逻辑-令a = 1。a ===(3 || 1)为假,为什么?

1长度字符串比较给出的结果与字符比较给出的结果不同...为什么?

为什么比较字符串0(n)但比较数字0(1)?

Scala:为什么l1 ::: l2与l1.:::(l2)不相等?

为什么gen1 / gen2集合比gen0慢?

为什么即使所有的 FIRST 集合都相同,这个文法还是 LL(1)?

(1至4).toSet和(1至4).to [scala.collection.immutable.Set]之间的Scala差异?

有效地比较Scala集合中两个的所有组合

为什么使用时不工作的indexOf不同的是VS比较它为-1?

在比较字符时,为什么Java StringLatin1.regionMatchesCI方法执行toUpperCase()而不是toLowerCase()?

为什么nodejs / express中的cookie签名使用sha1-hashing比较签名?

插入排序下限,为什么它与`1 /(2 ^ n)`比较?

为什么(-1 >>> 32)= -1?

为什么1 >> 32 == 1?

为什么1:[[]]等于(1:[]):[]?