加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么Buffer和List对象相等(即使它们来自不同的类)?

发布时间:2020-12-16 08:50:01 所属栏目:安全 来源:网络整理
导读:scala import scala.collection.mutable.Bufferimport scala.collection.mutable.Bufferscala val b = Buffer(1,2,3)b: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1,3)scala val l = List(1,3)l: List[Int] = List(1,3)scala b == lres1: Boolean
scala> import scala.collection.mutable.Buffer
import scala.collection.mutable.Buffer

scala> val b = Buffer(1,2,3)
b: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1,3)

scala> val l = List(1,3)
l: List[Int] = List(1,3)

scala> b == l
res1: Boolean = true

我想知道为什么Buffer和List对象可以与true结果进行比较?

我一直认为,因为他们来自不同的阶级,所以在比较时他们必须是假的.有人可以解释一下,为什么这样实现?

解决方法

从 http://www.scala-lang.org/docu/files/collections-api/collections_41.html起

The collection libraries have a uniform approach to equality and hashing. The idea is,first,to divide collections into sets,maps,and sequences. Collections in different categories are always unequal. For instance,Set(1,3) is unequal to List(1,3) even though they contain the same elements. On the other hand,within the same category,collections are equal if and only if they have the same elements (for sequences: the same elements in the same oder). For example,List(1,3) == Vector(1,3),and HashSet(1,2) == Treeset(2,1).

It does not matter for the equality check whether a collection is mutable or immutable. (…)

所以这是因为scala.collection.mutable.Buffer和List属于同一类别(序列),然后将相等定义为具有相同的元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读