Commons Collections僥楼永芝?匯?
扮寂:2011-07-20 鴬人坩 Phinecos
public interface Bag extends Collection
{
int getCount(Object object);
boolean add(Object object);
boolean add(Object object, int nCopies);
boolean remove(Object object);
boolean remove(Object object, int nCopies);
Set uniqueSet();
int size();
boolean containsAll(Collection coll);
boolean removeAll(Collection coll);
boolean retainAll(Collection coll);
Iterator iterator();
}
public interface SortedBag extends Bag
{
public Comparator comparator();
public Object first();
public Object last();
}
public abstract class DefaultMapBag implements Bag
{
private Map _map = null;//久蚊方象贋刈曝
private int _total = 0; //圷殆悳倖方
private int _mods = 0;//俐個肝方
public DefaultMapBag() {
}
protected DefaultMapBag(Map map) {
setMap(map);
}
public boolean add(Object object) {
return add(object, 1);
}
public boolean add(Object object, int nCopies) {
_mods++;
if (nCopies > 0) {
int count = (nCopies + getCount(object));
_map.put(object, new Integer(count));
_total += nCopies;
return (count == nCopies);
} else {
return false;
}
}
public boolean addAll(Collection coll) {
boolean changed = false;
Iterator i = coll.iterator();
while (i.hasNext()) {
boolean added = add(i.next());
changed = changed || added;
}
return changed;
}
public void clear() {
_mods++;
_map.clear();
_total = 0;
}
public boolean contains(Object object) {
return _map.containsKey(object);
}
public boolean containsAll(Collection coll) {
return containsAll(new HashBag(coll));
}
public boolean containsAll(Bag other) {
boolean result = true;
Iterator i = other.uniqueSet().iterator();
while (i.hasNext()) {
Object current = i.next();
boolean contains = getCount(current) >= other.getCount(current);
result = result && contains;
}
return result;
}
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Bag == false) {
return false;
}
Bag other = (Bag) object;
if (other.size() != size()) {
return false;
}
for (Iterator it = _map.keySet().iterator(); it.hasNext();) {
Object element = it.next();
if (other.getCount(element) != getCount(element)) {
return false;
}
}
return true;
}
public int hashCode() {
return _map.hashCode();
}
public boolean isEmpty() {
return _map.isE
|