首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java MAP 中如果 键相同就让值相加是如何做到的呢?了

2012-08-13 
java MAP 中如果 键相同就让值相加是怎么做到的呢?请教各位了!做法是先通过键从Map中将值取出来然后通过if

java MAP 中如果 键相同就让值相加是怎么做到的呢?请教各位了!
做法是先通过键从Map中将值取出来
然后通过if else 来判断
if存在
则进行相加
else
直接存入

[解决办法]
这样?
如果每次不是加1,只要你知道是加几就行

Java code
import java.net.URL;import java.util.*;public class URLCount{    public static void main(String[] args) throws Exception {        List<URL> urls = Arrays.asList(                new URL("http://www.google.com"),        new URL("http://www.csdn.net"),        new URL("http://www.google.com"),        new URL("http://www.csdn.net"),        new URL("http://www.google.com"),        new URL("http://www.google.com"),        new URL("http://www.csdn.net"),        new URL("http://www.csdn.net"),        new URL("http://www.google.com"),        new URL("http://www.google.com")    );        Counter<URL> urlCounter = new Counter<URL>();        for(URL url : urls)      urlCounter.addCount(url, 1);        for(URL key : urlCounter)      System.out.println(key + " : " + urlCounter.getCount(key));  }}class Counter<K> implements Iterable<K> {    private Map<K, Count> counts = new HashMap<K, Count>();    void addCount(K key, int count) {        if( key == null ) throw new NullPointerException();        Count c = counts.get(key);    if( c == null ) {            c = new Count();      counts.put(key, c);    }    c.add(count);  }    int getCount(K key) {        if( key == null ) throw new NullPointerException();        Count c = counts.get(key);    return c == null ? 0 : c.get();  }    @Override  public Iterator<K> iterator() {        return counts.keySet().iterator();  }}class Count {  private int count;  public Count() {    this.count = 0;  }  public void add(int count) {    this.count += count;  }    public int get() {        return count;  }} 

热点排行