Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

java - 给定哈希图中的键,如何更新值?(How to update a value, given a key in a hashmap?)

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

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

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.

(哈希表的正确行为是为其分配一个不同的位置,或在当前存储桶中列出该列表。)

  ask by laertis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

(请注意,这使用自动装箱。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...