【转载】Java高效计数器

原文链接:https://blog.csdn.net/renfufei/article/details/14120775
翻译人员: 铁锚
翻译时间: 2013年11月3日
原文链接: Efficient Counter in Java

我们经常使用 HashMap作为计数器(counter)来统计数据库或者文本中的某些东西.
本文将使用HashMap来实现计数器的3种不同方式进行对比。

  1. 新手级计数器
    如果使用这一类别的计数器,那么代码大致如下所示:
翻译人员: 铁锚
翻译时间: 2013113日
原文链接: 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);  
        }  
    }  
}  
  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));  
        }  
    }  
}  
  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);  
        }  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值