// Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
package edu.berkeley.sbp.util;
import java.util.*;
/** a mapping from keys of type K to sets of values of type T */
public final class HashMapBag implements MapBag {
private final HashMap> hm = new HashMap>();
public void add(K k, V v) {
HashSet hs = hm.get(k);
if (hs==null) hm.put(k, hs = new HashSet());
size -= hs.size();
hs.add(v);
size += hs.size();
}
public void addAll(K k, Iterable iv) {
for(V v : iv) add(k, v);
}
public HashSet getAll(K k) {
HashSet ret = hm.get(k);
if (ret==null) return new HashSet();
return ret;
}
public void remove(K k, V v) {
if (hm.get(k)==null) return;
HashSet hs = hm.get(k);
if (hs==null) return;
size -= hs.size();
hs.remove(v);
size += hs.size();
}
public void removeAll(K k, Iterable iv) {
for(V v : iv) remove(k, v);
}
public void clear() { hm.clear(); }
public boolean contains(K k, V v) {
return hm.get(k)!=null && hm.get(k).contains(v);
}
public void addAll(HashMapBag hmb) {
for(K k : hmb) addAll(k, hmb.getAll(k));
}
public void removeAll(HashMapBag hmb) {
for(K k : hmb) removeAll(k, hmb.getAll(k));
}
public Iterator iterator() { return hm.keySet().iterator(); }
public int size() { return size; }
private int size = 0;
}