//此类提供 Set 接口的骨干实现,从而最大限度地减少了实现此接口所需的工作 JDK1.7 java.util
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
//构造方法
protected AbstractSet() {
}
//比较指定对象与此 set的相等性
public boolean equals(Object o) {
if (o == this)
return true;//引用相等则必然相等
if (!(o instanceof Set))
return false;//必须是set或其子类
Collection c = (Collection) o;
if (c.size() != size())
return false;//长度不等则false
try {
return containsAll(c);//比较
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
//返回hashCode
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
//从此 set中移除包含在指定 collection 中的所有元素
public boolean removeAll(Collection<?> c) {
boolean modified = false;
if (size() > c.size()) {
for (Iterator<?> i = c.iterator(); i.hasNext(); )//如果原集合中元素较多,则迭代c
modified |= remove(i.next());
} else {
for (Iterator<?> i = iterator(); i.hasNext(); ) {//如果c中元素较多,则迭代c
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
}
return modified;
}
}
Java集合之AbstractSet
最新推荐文章于 2021-03-06 06:59:44 发布