lyn*_*nks 5 java equals hashmap hashcode
我有以下代码来计算数组中不同字符串的实例;
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);
}
Run Code Online (Sandbox Code Playgroud)
这是一种正确的做法吗?对于一项简单的任务来说似乎有点啰嗦.的HashMap,因为我会被串编入索引的结果对我有用.
我很担心这条线
else wordCounts.put(w, i + 1);
Run Code Online (Sandbox Code Playgroud)
key-value由于这个事实,可能会插入第二对
new Integer(i).equals(new Integer(i + 1));
Run Code Online (Sandbox Code Playgroud)
会是假的,所以两个Integers人最终会在同一个String钥匙桶下面,对吧?或者我只是过度思考自己陷入困境?
您的代码将工作 -但它是易于使用HashMultiset的番石榴.
// Note: prefer the below over "String words[]"
String[] words = {"the","cat","in","the","hat"};
Multiset<String> set = HashMultiset.create(Arrays.asList(words));
// Write out the counts...
for (Multiset.Entry<String> entry : set.entrySet()) {
System.out.println(entry.getElement() + ": " + entry.getCount());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11564 次 |
| 最近记录: |