gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:08:01 25 4
gpt4 key购买 nike

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, 2, 3)

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 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, 2, 3) is unequal to List(1, 2, 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, 2, 3) == Vector(1, 2, 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属于同一类别(序列),然后将相等定义为具有相等的元素。

关于list - 为什么Buffer和List对象相等(即使它们来自不同的类)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com