给定哈希图中的键,如何更新值? [英] How to update a value, given a key in a hashmap?

查看:110
本文介绍了给定哈希图中的键,如何更新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在Java中有一个HashMap<String, Integer>.

Suppose we have a HashMap<String, Integer> in Java.

对于找到的每个字符串,如何更新(递增)字符串键的整数值?

How do I update (increment) the integer-value of the string-key for each existence of the string I find?

一个人可以删除并重新输入该对,但是开销会成为问题.
另一种方法是只放置新的一对,而旧的将被替换.

One could remove and reenter the pair, but overhead would be a concern.
Another way would be to just put the new pair and the old one would be replaced.

在后一种情况下,如果哈希码与我尝试插入的新密钥发生冲突,该怎么办?哈希表的正确行为是为其分配一个不同的位置,或在当前存储桶中列出该列表.

In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.

推荐答案

map.put(key, map.get(key) + 1);

应该没问题.它将更新现有映射的值.请注意,这使用自动装箱.

should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing.

这篇关于给定哈希图中的键,如何更新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆