【问题标题】:Priority Queue of HashMaps in ScalaScala中HashMap的优先级队列
【发布时间】:2015-03-25 17:20:06
【问题描述】:

我正在尝试更新我的 HashMaps 优先队列中的一个元素的值,但没有成功。这是我的做法:

def HashMapOrdering = new Ordering[HashMap[Int,Int]] {

  def compare(a : HashMap[Int,Int], b : HashMap[Int,Int]) = b.valuesIterator.next().compare(a.valuesIterator.next())

}

def main(args: Array[String]) {

  var seeds = PriorityQueue[HashMap[Int, Int]]()(HashMapOrdering)
  seeds.enqueue(HashMap(4 -> 4), HashMap(234 -> 5), HashMap(78 -> 6), HashMap(89 -> 1))

  seeds.find(x => x.get(89) == 1) match {

    case Some(hashMap: HashMap[Int, Int]) => hashMap.remove(77); hashMap.put(77,32)
    case None => println("Not found")

  }

}

不幸的是,我总是收到“未找到”消息。关于我做错了什么或如何更新哈希值的任何想法?

【问题讨论】:

    标签: scala hashmap priority-queue


    【解决方案1】:

    显然你有一个类型不匹配。如果您查看get 函数的定义,您会看到以下内容(http://www.scala-lang.org/api/2.11.6/index.html#scala.collection.mutable.HashMap):

    def get(key: A): Option[B]
    

    这意味着,在您输入为Option[Int] 的情况下,它会返回值。因此,将您的正确条件参数包装在 Option monad 中:

    seeds.find(x => x.get(89) == Some(1)) match {
        case Some(hashMap: HashMap[Int, Int]) => {
            hashMap.remove(77)
            hashMap.put(77,32)
        }
        case None => println("Not found")
    }
    

    按预期工作。

    附:忘记了关于更新的问题:您可以使用update 函数而不是使用removeputhashMap.update(77, 32)

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 2013-03-25
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多