TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
使用泛型T代表所要统计信息的类,应该有效的定义该类的equals()和hasCode()。
statistics()方法进行关键字统计。
getAllKeysStatistics()方法返回底层的Map,即所有的键-值对。
getAllKeys()方法返回所有key组成的Set。
getKeyStatistics()方法返回单个确定Key的统计信息。
测试例使用10000个随机整型数(0~9)来统计它们的产生频率。- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- public class Statistics< T> {
- private Map< T, Integer> m = new HashMap< T, Integer>();
- public void statistics(T t) {
- Integer freq = m.get(t);
- m.put(t, freq == null ? 1 : freq + 1);
- }
- public void getAllKeysStatistics() {
- System.out.println(m);
- }
- public void getAllKeys() {
- System.out.println(m.keySet());
- }
- public int getKeyStatistics(T t) {
- return m.get(t) == null ? 0 : m.get(t);
- }
- public static void main(String[] args) {
- Random rand = new Random();
- Statistics< Integer> s = new Statistics< Integer>();
- for (int i = 0; i < 10000; i++) {
- // Produce a number between 0 and 9:
- int r = rand.nextInt(10);
- s.statistics(r);
- }
- s.getAllKeysStatistics();
- s.getAllKeys();
- System.out.println("Key -1:" + s.getKeyStatistics(-1));
- System.out.println("Key 0:" + s.getKeyStatistics(0));
- }
- }
复制代码 结果:
{0=1038, 1=1014, 2=939, 3=987, 4=977, 5=974, 6=1036, 7=974, 8=1075,9=986}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Key -1:0
Key 0:1038
本文出自 “子 孑” 博客,请务必保留此出处 http://zhangjunhd.blog.51cto.com/113473/69949
源码下载:http://file.javaxxz.com/2014/10/31/235558000.zip |
|