抽象set继承了抽象集合,只是额外重写了equal和hashCode方法 抽象set是set接口的扩展 public abstract class AbstractSet extends AbstractCollection implements Set { protected AbstractSet() { } 两个set是否相等的比较方式,先比较引用是否相同,否则继续比较大小是否一致,继而对两个集合中每个元素进行一一比较是否相等 public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection c = (Collection) o; if (c.size() != size()) return false; try { return containsAll(c); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } 所有继承了这个抽象set的类的hashCode计算方法: 是对set中每个元素的hashcode值进行累加 public int hashCode() { int h = 0; Iterator i = iterator(); while (i.hasNext()) { E obj = i.next(); if (obj != null) h += obj.hashCode(); } return h; } 如果当前的set大小大于传入进来的set,那么用传进来的参数作为遍历因子在当前set中移除 否则以当前set的大小作为遍历因子去做移除操作 也就是说,谁的大小比较小,就以谁为遍历因子去另一个set中移除操作 public boolean removeAll(Collection> c) { boolean modified = false; if (size() > c.size()) { for (Iterator> i = c.iterator(); i.hasNext(); ) modified |= remove(i.next()); } else { for (Iterator> i = iterator(); i.hasNext(); ) { if (c.contains(i.next())) { i.remove(); modified = true; } } } return modified; } }