CommonsCollections学习笔记(一)
来源:优易学  2011-1-3 12:25:03   【优易学:中国教育考试门户网】   资料下载   IT书店

  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.isEmpty();
  }

[1] [2] [3] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训