gpt4 book ai didi

scala - 在 Scala 中指定 HashMap 的大小

转载 作者:行者123 更新时间:2023-12-03 02:02:26 24 4
gpt4 key购买 nike

我正在使用 Scala 的可变 HashMap 逐步添加数百万个键值对。这些 HashMap 的大小调整现在是我的程序中最慢的部分。我如何告诉 Scala 从一开始就创建一个非常大的 HashMap,以便它(几乎)永远不需要调整大小?

如果有任何建议能够提出另一个适合我的需求的 Scala/Java 集合,我也将不胜感激。添加新的键值对和检索给定键的值应该都可以在大约恒定的时间内完成。

最佳答案

可能的方法之一:

import scala.collection.mutable.{HashTable, DefaultEntry}

trait BigHashTable[A, B] extends HashTable[A, DefaultEntry[A, B]] {
override def initialSize: Int = 1024 // 16 - by default
}

val x = new HashMap[Int, String] with BigHashTable[Int, String]

另一个:

class MyHashMap[A, B](initSize : Int) extends HashMap[A, B] {
override def initialSize: Int = initSize // 16 - by default
}

val x = new MyHashMap[Int, String](1024)

关于scala - 在 Scala 中指定 HashMap 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22654592/

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