@xmruibi
2015-02-14T21:37:19.000000Z
字数 1585
阅读 646
Data_Structure
Set & AbstractSet
// In Set interface, it only come with the implementations in collection interfacepublic interface Set<E> extends Collection<E> {int size();boolean isEmpty();boolean contains(Object o);Iterator<E> iterator();Object[] toArray();<T> T[] toArray(T[] a);boolean add(E e);boolean remove(Object o);boolean containsAll(Collection<?> c);boolean addAll(Collection<? extends E> c);boolean retainAll(Collection<?> c);boolean removeAll(Collection<?> c);void clear();boolean equals(Object o);int hashCode();}
Implements some method for subclasses of Set
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {protected AbstractSet() {}/***** compare two object *******/public boolean equals(Object o) {if (o == this)// the same referencereturn true;if (!(o instanceof Set)) // type must be the samereturn false;Collection c = (Collection) o;if (c.size() != size()) // compare the sizereturn false;try {return containsAll(c);// compare the insided elements} catch (ClassCastException unused) {return false;} catch (NullPointerException unused) {return false;}}/***** hashCode Implementation *****/public int hashCode() {int h = 0;Iterator<E> i = iterator();while (i.hasNext()) {E obj = i.next();if (obj != null)h += obj.hashCode(); // ? why add}return h;}/***** remove all elements in collection *****/public boolean removeAll(Collection<?> c) {boolean modified = false;// choose the shorter one to remove elementif (size() > c.size()) {for (Iterator<?> i = c.iterator(); i.hasNext(); )modified |= remove(i.next()); // boolean operation '|'} else {for (Iterator<?> i = iterator(); i.hasNext(); ) {if (c.contains(i.next())) {i.remove();modified = true;}}}return modified;}}