package yi.ds;

import java.util.*;

/**
 * AccumulatorHashMap handles a hashmap with its value is an integer which can
 * be used as counter
 */

public class CounterHashMap extends HashMap implements Comparator{
  public void increaseCount(Object key) {
    Integer counter = (Integer)get(key);
    if (counter == null) {  // if there is no corresponding accumulator yet
      counter = new Integer(0);
    }
    counter = new Integer(counter.intValue() + 1);
    put(key, counter);
  }

  public void increaseCount(Collection list) {
    for (Iterator i=list.iterator(); i.hasNext();) {
      increaseCount(i.next());
    }
  }

  public int getCount(Object key) {
    Integer counter = (Integer)get(key);
    if (counter == null) {  // if there is no corresponding accumulator yet
      return 0;
    }
    return counter.intValue();
  }

  public int compare(Object o1, Object o2) {
    int score1 = getCount(o1);
    int score2 = getCount(o2);
    if (score1 > score2) return 1;
    else if (score1 < score2) return -1;
    return 0;
  }

}