java实现一个简单的计数器


package com.fengunion.sf;

import org.junit.platform.commons.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CountUtil {
private static Map<String, Integer> map = null;

static {
map = new HashMap<String, Integer>();
}


/**
*
* 实现一个简单的计数器
* @param str
* @return
*/
public static int countNum(String str) {
if (StringUtils.isNotBlank(str)) {
Integer count = map.get(str);
if (count == null) {
count = 1;
} else {
count++;
}
map.put(str, count);
}
return map.get(str);
}


public static void main(String[] args) {

for(int i = 0; i<new Random().nextInt(50); i++){
countNum("a");
}
countNum("a");
countNum("b");
countNum("b");
countNum("c");
int counta = countNum("a");
int countb = countNum("b");
countNum("c");
countNum("c");
int countc = countNum("c");

System.out.println(" countaNum: " + counta + " countbNum: " + countb + " countcNum: " + countc);


}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM