概述
此类提供了Set接口的基本实现,以最大程度地减少实现此接口所需的工作。通过扩展此类来实现集合的过程,与通过扩展AbstractCollection来实现Collection的过程相同。不同之处在于,此类的子类中的所有方法和构造函数都必须服从Set接口(例如,add方法必须不允许将一个对象的多个实例添加到集合中)。请注意,此类不会覆盖AbstractCollection类中的任何实现。它只是添加了equals和hashCode的实现。
继承关系
public abstract class AbstractSet extends AbstractCollection implements Set
继承自AbstractCollection 实现了Set接口
成员属性
构造器
关键方法
equals()
比较指定对象与此设置的相等性。如果给定对象也是一个集合,两个集合具有相同的大小,并且给定集合的每个成员都包含在此集合中,则返回 true 。这样可以确保equals方法在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;
}
}
hashCode()
返回此集合的哈希码值。集合的哈希码定义为集合中元素的哈希码之和,其中null元素的哈希码定义为零。
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;
}
removeAll()
删除该对象中,所有同时处于目标Collection中的元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(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;
}
希望和大家多多交流
我16年毕业以后,做的是前端,目前打算深入学习java开发。内容有任何问题,欢迎各位小伙伴们指正,也希望小伙伴们给我点赞和关注,给我留言,一起交流讨论,共同进步。