gpt4 book ai didi

scala - hasDefiniteSize 和 knownSize

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

我正在浏览 Scala 中的 List 方法。

val mylist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 10)

hasDefiniteSizeknownSize 让我很困惑。

对于 ListhasDefiniteSize 返回 trueknownSize 返回 -1

这些方法背后的确切理论是什么?

最佳答案

此方法由 List 的父类(super class)定义,该父类(super class)在可能无穷无尽的集合中很常见(如 Streams、LazyLists 和 迭代器s)。

有关更多详细信息,我相信文档说得最好。

这是 hasDefiniteSize in version 2.13.1 的那个:

Tests whether this collection is known to have a finite size. Allstrict collections are known to have finite size. For a non-strictcollection such as Stream, the predicate returns true if all elementshave been computed. It returns false if the stream is not yetevaluated to the end. Non-empty Iterators usually return false even ifthey were created from a collection with a known finite size.

Note: many collection methods will not work on collections of infinitesizes. The typical failure mode is an infinite loop. These methodsalways attempt a traversal without checking first that hasDefiniteSizereturns true. However, checking hasDefiniteSize can provide anassurance that size is well-defined and non-termination is not aconcern.

请注意,hasDefiniteSize 已弃用,并显示以下消息:

(Since version 2.13.0) Check .knownSize instead of .hasDefiniteSizefor more actionable information (see scaladoc for details)

documentation for knownSize进一步说明:

The number of elements in this collection, if it can be cheaplycomputed, -1 otherwise. Cheaply usually means: Not requiring acollection traversal.

List 是一个链表的实现,这就是为什么 List(1, 2, 3).hasDefiniteSize 返回 true(集合不是无限的)但是 List(1, 2, 3).knownSize 返回 -1 (计算集合大小需要遍历整个列表)。

关于scala - hasDefiniteSize 和 knownSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61443544/

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