package Tools;

import java.util.*;

/**
 * A Map whose members are sets.
 */
public class MultiMap {
	HashMap map = new HashMap();

	/**
	 * The nicest operation of this class: Add object <code>to</code>
	 * to the set of objects identified by the key <code>from</code>.
	 */
	public void add(Object from, Object to) {
		HashSet targetList = (HashSet) map.get(from);
		if (targetList==null) {
			targetList = new HashSet();
			map.put(from, targetList);
		}
		targetList.add(to);
	}

	/**
	 * Get the set of objects associated with the key
	 * <code>from</code>.
	 */
	public Set getSet(Object from) {
		Set s = (Set) map.get(from);
		if (s==null) {
			return new HashSet();
		}
		return s;
	}

	// this is a slow call
	public int size() {
		int total=0;
		Iterator iter = map.keySet().iterator();
		while (iter.hasNext()) {
			Set set = (Set) map.get(iter.next());
			total += set.size();
		}
		return total;
	}

	public int size(Object from) {
		Set s = (Set) map.get(from);
		if (s==null) {
			return 0;
		}
		return s.size();
	}

	public Iterator iterator(Object from) {
		HashSet targetList = (HashSet) map.get(from);
		if (targetList==null) {
			// empty iterator
			return (new HashSet()).iterator();
		} else {
			return targetList.iterator();
		}
	}

	public Set keys() {
		return map.keySet();
	}
}
