一、概述
Collection接口继承了Iterable接口,拥有了获取迭代器和循环方法,同时定义了集合基本操作方法,AbstractCollection作为Collection接口的实现类,进一步提供了其中部分方法的默认实现,简化了为实现类为重写Collection接口方法的工作量。框架关系图如下所示:
值得一提的是,对集合框架中各接口和抽象类的认识,有利于提升对整个集合框架的理解,有兴趣的同学还可以花几分钟简要看看以下文章:
1、简述Iterable与Iterator接口
2、简述Collection接口
二、源码
AbstractCollection抽象类提供了Collection接口的框架实现,以最小化实现此接口所需的工作量。
通过查阅源码可以了解到,AbstractCollection添加了以下几个方法的默认实现:
1、isEmpty
public boolean isEmpty() {
return size() == 0;
}
2、contains
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}
3、toArray
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
4、add
public boolean add(E e) {
throw new UnsupportedOperationException();
}
add方法直接抛出异常,因此不能直接调用,需要重写。
5、remove
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
6、containsAll
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
7、addAll
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
8、removeAll
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
9、retainAll
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
10、clear
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
10、toString
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
因此,如果要实现一个不可修改的集合(不需要增删操作),只需要拓展这个类并重写迭代器方法(hasNext()和next())和size()方法。
如果要实现一个可修改的集合(需要增删操作),必须要重写add方法以及迭代器的remove方法。
如果需要构造自定义的集合,可以重写其中的所有方法。
参考资料:
https://blog.youkuaiyun.com/GDUT_Trim/article/details/117572245