日期:2014-05-20 浏览次数:20791 次
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; } }