AbstractCollection
光从名字就能看出,这是一个实现了Collection接口的抽象类,当然我们不能光看一个名字就断定他的本质。所以很有必要看下源码是如何的,奉上源码:
public abstract class AbstractCollection<E> implements Collection<E>
很好,看样子我猜的非常准,。continue.
我们先从插入方法中的add方法开始,二话不说,先源码:
/**
* {@inheritDoc}
*
* <p>This implementation always throws an
* <tt>UnsupportedOperationException</tt>.
*
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @throws IllegalStateException {@inheritDoc}
*/
public boolean add(E e) {
throw new UnsupportedOperationException();
}
唉呀呀呀,,,,,,发现没什么好看的,我觉得注释很有意思,他已经把这个方法可能碰到的异常都列举出来了,厉害。
看addAll方法:
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
瞄一眼后,觉得还是跳过为妙。next method!
好,clear方法,源码先:
public void clear() {
Iterator<E> it = iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
哦,原来源码的clear是这样子实现的,相当的通用呀!赞一个。next!
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;
}
在这里不难发现,集合可以插入为null的对象。然后,对于是否包含的判断的条件为equals是否为true。
containsAll方法
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
哦,原来是这样子,很简单嘛。下一个
isEmpty方法,看源码:
public boolean isEmpty() {
return size() == 0;
}
看下size方法
public abstract int size();
size方法原来是交给具体实现类来实现的呀,只要判断下size的返回值是不是为零就可以了,很简单。
Iterator方法
public abstract Iterator<E> iterator();
飞过,
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;
}
原来是通过迭代器来实现删掉操作的呀,厉害。呃,去挑个有意思的实现看看
retainAll方法
public boolean retainAll(Collection<?> c) {
boolean modified = false;
Iterator<E> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
瞄了几眼后,发现这个方法的功能是求交集,有意思。
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;
}
我靠,迭代器真是太厉害了,集合里不能少了迭代器这个神器。