原文链接:https://blog.csdn.net/renfufei/article/details/14120775
翻译人员: 铁锚
翻译时间: 2013年11月3日
原文链接: Efficient Counter in Java
我们经常使用 HashMap作为计数器(counter)来统计数据库或者文本中的某些东西.
本文将使用HashMap来实现计数器的3种不同方式进行对比。
- 新手级计数器
如果使用这一类别的计数器,那么代码大致如下所示:
翻译人员: 铁锚
翻译时间: 2013年11月3日
原文链接: Efficient Counter in Java
我们经常使用 HashMap作为计数器(counter)来统计数据库或者文本中的某些东西.
本文将使用HashMap来实现计数器的3种不同方式进行对比。
1. 新手级计数器
如果使用这一类别的计数器,那么代码大致如下所示:
[java] view plain copy
String source = "my name is name me and your name is her first her";
String[] words = source.split(" ");
// 新手级计数器
public static void testNaive(String[] words){
HashMap<String, Integer> counter = new HashMap<String, Integer>();
for (String w : words) {
if(counter.containsKey(w)){
int oldValue = counter.get(w);
counter.put(w, oldValue+1);
} else {
counter.put(w, 1);
}
}
}
- 入门级计数器
那么我们自然需要使用一个可变的整数来避免创建太多个Integer对象.可变整数类可以如下面所示来定义:
// 可变Integer
public static final class MutableInteger{
private int val;
public MutableInteger(int val){
this.val = val;
}
public int get(){
return this.val;
}
public void set(int val){
this.val = val;
}
// 为了方便打印
public String toString() {
return Integer.toString(val);
}
}
// 入门级计数器
public static void testBetter(String[] words){
HashMap<String, MutableInteger> counter = new HashMap<String, MutableInteger>();
for (String w : words) {
if(counter.containsKey(w)){
MutableInteger oldValue = counter.get(w);
oldValue.set(oldValue.get()+1); // 因为是引用,所以减少了一次HashMap查找
} else {
counter.put(w, new MutableInteger(1));
}
}
}
- 卓越级计数器
HashMap 的 put(key,value) 方法会返回key对应的当前value.了解这个特性,我们可以利用原有值来进行递增,并不需要多次的查找.
public static void testEfficient(String[] words){
HashMap<String, MutableInteger> counter = new HashMap<String, MutableInteger>();
for (String w : words) {
MutableInteger initValue = new MutableInteger(1);
// 利用 HashMap 的put方法弹出旧值的特性
MutableInteger oldValue = counter.put(w, initValue);
if(oldValue != null){
initValue.set(oldValue.get() + 1);
}
}
}