首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala中的mutable.HashTable类

Scala中的mutable.HashTable类
EN

Stack Overflow用户
提问于 2017-12-04 18:26:55
回答 1查看 1.5K关注 0票数 2

在线文档并没有给出太多关于它的说明(http://www.scala-lang.org/api/2.12.0/scala/collection/mutable/HashTable.html),也不可能找到任何使用它的例子。我想知道如何将元素放入mutable.HashTable中。

在我可以使用的研究和删除操作中,是否有相同时间复杂度的数据结构?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-04 18:46:28

mutable.HashTable是一种特质。

代码语言:javascript
复制
trait HashTable[A, Entry >: Null <: HashEntry[A, Entry]] extends HashTable.HashUtils[A]

默认负载因子为75%

代码语言:javascript
复制
private[collection] final def defaultLoadFactor: Int = 750

使用数组来实现,

代码语言:javascript
复制
protected var table: Array[HashEntry[A, Entry]] = new Array(initialCapacity)

1)您必须使用HashTable**,的实现,这些实现是** mutable.HashMap mutable.LinkedHashMap**.**

例如,

代码语言:javascript
复制
scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> new HashMap[String, String]
res9: scala.collection.mutable.HashMap[String,String] = Map()

添加元素

代码语言:javascript
复制
scala> res9+= "order-id-1" -> "delivered"
res10: res9.type = Map(order-id-1 -> delivered)

scala> res9
res11: scala.collection.mutable.HashMap[String,String] = Map(order-id-1 -> delivered)

访问元素

代码语言:javascript
复制
scala> res9("order-id-1")
res12: String = delivered

写复杂度应该与hashmap数据结构中的O(1)相同。找到哈希码并将其添加到条目数组中。

代码语言:javascript
复制
  def += (kv: (A, B)): this.type = {
    val e = findOrAddEntry(kv._1, kv._2)
    if (e ne null) e.value = kv._2
    this
  }

  protected def findOrAddEntry[B](key: A, value: B): Entry = {
    val h = index(elemHashCode(key))
    val e = findEntry0(key, h)
    if (e ne null) e else { addEntry0(createNewEntry(key, value), h); null }
  }

  private[this] def findEntry0(key: A, h: Int): Entry = {
    var e = table(h).asInstanceOf[Entry]
    while (e != null && !elemEquals(e.key, key)) e = e.next
    e
  }

  private[this] def addEntry0(e: Entry, h: Int) {
    e.next = table(h).asInstanceOf[Entry]
    table(h) = e
    tableSize = tableSize + 1
    nnSizeMapAdd(h)
    if (tableSize > threshold)
      resize(2 * table.length)
  }

2.如果使用LinkedHashMap ,则使用链接条目来保持插入顺序。

代码语言:javascript
复制
  @transient protected var firstEntry: Entry = null
  @transient protected var lastEntry: Entry = null

例如,

代码语言:javascript
复制
scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap

scala> LinkedHashMap[String, String]()
res0: scala.collection.mutable.LinkedHashMap[String,String] = Map()

scala> res0 += "line-item1" -> "Delivered" += "line-item2" -> "Processing"
res2: res0.type = Map(line-item1 -> Delivered, line-item2 -> Processing)

scala> res0
res3: scala.collection.mutable.LinkedHashMap[String,String] = Map(line-item1 -> Delivered, line-item2 -> Processing)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47639664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档