JDK17源码系列-AbstractSet接口源码解读
1、AbstractSet类图结构
2、AbstractSet是个抽象集合类
- equals() 方法 比较两个集合是否相等
public boolean equals(Object o) {
if (o == this) // 如果两个集合的引用(即内存地址)相同,返回true
return true;
if (!(o instanceof Set)) // 如果目标集合未实现Set接口,则返回false
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != size()) // 如果当前集合大小与目标集合大小不相等,则返回false
return false;
try {
// containsAll 存在父类AbstractCollection类中
return containsAll(c); // 当前集合是否完全包含(比较集合中每一个元素)目标集合,如果全包含,返回true,否则返回false
} catch (ClassCastException | 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;
}
- public boolean removeAll(Collection<?> c) 删除目标集合
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
if (size() > c.size()) { // 如果当前集合大小大于目标集合c,则遍历目标集合c,从当前集合中删除目标集合中的每个元素
for (Object e : c)
modified |= remove(e);
} else {
// 如果当前集合大小<=目标集合,则遍历当前集合,判断目标集合中是否包含遍历的元素,如果包含,则从当前集合中删除该元素
for (Iterator<?> i = iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
}
return modified;
}