[关闭]
@xmruibi 2015-02-14T21:37:19.000000Z 字数 1585 阅读 646

Set Interface & Abstract Set

Data_Structure


Set & AbstractSet

1. Set Interface

  1. // In Set interface, it only come with the implementations in collection interface
  2. public interface Set<E> extends Collection<E> {
  3. int size();
  4. boolean isEmpty();
  5. boolean contains(Object o);
  6. Iterator<E> iterator();
  7. Object[] toArray();
  8. <T> T[] toArray(T[] a);
  9. boolean add(E e);
  10. boolean remove(Object o);
  11. boolean containsAll(Collection<?> c);
  12. boolean addAll(Collection<? extends E> c);
  13. boolean retainAll(Collection<?> c);
  14. boolean removeAll(Collection<?> c);
  15. void clear();
  16. boolean equals(Object o);
  17. int hashCode();
  18. }

2. Abtract Set Interface

Implements some method for subclasses of Set

  1. public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
  2. protected AbstractSet() {
  3. }
  4. /***** compare two object *******/
  5. public boolean equals(Object o) {
  6. if (o == this)// the same reference
  7. return true;
  8. if (!(o instanceof Set)) // type must be the same
  9. return false;
  10. Collection c = (Collection) o;
  11. if (c.size() != size()) // compare the size
  12. return false;
  13. try {
  14. return containsAll(c);
  15. // compare the insided elements
  16. } catch (ClassCastException unused) {
  17. return false;
  18. } catch (NullPointerException unused) {
  19. return false;
  20. }
  21. }
  22. /***** hashCode Implementation *****/
  23. public int hashCode() {
  24. int h = 0;
  25. Iterator<E> i = iterator();
  26. while (i.hasNext()) {
  27. E obj = i.next();
  28. if (obj != null)
  29. h += obj.hashCode(); // ? why add
  30. }
  31. return h;
  32. }
  33. /***** remove all elements in collection *****/
  34. public boolean removeAll(Collection<?> c) {
  35. boolean modified = false;
  36. // choose the shorter one to remove element
  37. if (size() > c.size()) {
  38. for (Iterator<?> i = c.iterator(); i.hasNext(); )
  39. modified |= remove(i.next()); // boolean operation '|'
  40. } else {
  41. for (Iterator<?> i = iterator(); i.hasNext(); ) {
  42. if (c.contains(i.next())) {
  43. i.remove();
  44. modified = true;
  45. }
  46. }
  47. }
  48. return modified;
  49. }
  50. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注