AbstractSet 提供
Set 接口的骨干实现,从而最大限度地减少了实现此接口所需的工作,此类并没有重写
AbstractCollection 类中的任何实现。
它仅仅添加了
equals 和
hashCode 的实现。
AbstractQueue提供某些 Queue
操作的骨干实现。此类中的实现适用于基本实现不 允许包含 null 元素时。
//继承了AbstractCollection接口,实现了Set接口
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
protected AbstractSet() {//提供一个默认的构造函数
}
//比较是否相等
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);//通过containsAll方法判断
} 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;
}
//删除c里面的所有元素
public boolean removeAll(Collection<?> 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;
}
}
//继承了AbstractCollection接口,实现了Queue接口
public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> {
protected AbstractQueue() {//实现空的构造函数
}
public boolean add(E e) {//添加元素,调用offer来实现,调用失败抛出异常
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
public E remove() {//删除元素,通过poll方式实现,如果poll返回为空,则抛出异常
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public E element() {//通过peek来实现,如果peek返回元素为空,则抛出异常
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public void clear() {//删除所有元素
while (poll() != null)
;
}
//批量添加
public boolean addAll(Collection<? extends E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
}