问题描述
我有以下代码来计算数组中不同字符串的实例:
I have the following code to count the instances of different strings in an array;
String words[] = {"the","cat","in","the","hat"};
HashMap<String,Integer> wordCounts = new HashMap<String,Integer>(50,10);
for(String w : words) {
Integer i = wordCounts.get(w);
if(i == null) wordCounts.put(w, 1);
else wordCounts.put(w, i + 1);
}
这是做这件事的正确方法吗?对于一项简单的任务似乎有点冗长。 HashMap
结果对我很有用,因为我会用字符串对它进行索引。
Is this a correct way of doing it? It seems a bit long-winded for a simple task. The HashMap
result is useful to me because I will be indexing it by the string.
我很担心line
I am worried that the line
else wordCounts.put(w, i + 1);
可以插入第二个键值
由于这样的事实:
could be inserting a second key-value
pair due to the fact that
new Integer(i).equals(new Integer(i + 1));
会是假的,所以两个整数
会最终在同一个字符串
键桶之下,对吧?或者我只是想自己到了一个角落?
would be false, so two Integers
would end up under the same String
key bucket, right? Or have I just over-thought myself into a corner?
推荐答案
是的,你正在做正确的做法。如果提供了相同的密钥,HashMap将替换值。
Yes you are doing it correct way. HashMap replaces values if same key is provided.
从Java文档
From Java doc of HashMap#put
这篇关于使用HashMap来计算实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!