jdk源码阅读之AbstractSet

xiaoxiao2025-11-17  8

jdk源码阅读之AbstractSet

AbstractSet简介AbstractSet类图AbstractSet重要方法equalsremoveAll 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的代码很短,只有三个方法,大概用几分钟即可读完,方法和其他集合类也很相似,所以看起来没有什么难度。

说明

本文是本人撰写,如果本文让你有些许收获或感悟,我感到荣幸。如果对这篇文章有不同的意见或发现错误,欢迎留言纠正或者联系我:zlh8013gsf@126.com

转载请注明原文地址: https://www.6miu.com/read-5039775.html

最新回复(0)