jdk源碼閱讀之AbstractSet
AbstractSet簡介
此類提供 Set 接口的骨幹實現,從而最大限度地減少了實現此接口所需的工作。
AbstractSet類圖
AbstractSet重要方法
equals
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;
}
}
這個判斷相等的方法會比較每一個元素是否相同,比較是否相同會調用contains方法。
removeAll
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;
}
移除的方法是使用迭代器的remove方法。
AbstractSet閱讀感受
AbstractSet的代碼很短,只有三個方法,大概用幾分鐘即可讀完,方法和其他集合類也很相似,所以看起來沒有什麼難度。
說明
本文是本人撰寫,如果本文讓你有些許收穫或感悟,我感到榮幸。如果對這篇文章有不同的意見或發現錯誤,歡迎留言糾正或者聯繫我:[email protected]