各种关系

浅蓝色是接口
深蓝色是类

collection的关系
collection的关系

Collection接口

继承于接口Iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
//删除所有与c中相同的元素
boolean removeAll(Collection<?> c);
//保留与c中相同的元素,即删除与c中不同的元素
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}

Iterator接口

1
2
3
4
5
6
7
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}

访问元素

Iterator可以用于访问元素

1
2
3
4
5
6
Collection<String> c = ...;
Iterator<String> it = c.iterator();
while(it.hasNext()){
String s = it.next();
//do something
}

访问元素还可用for each,并且推荐使用for each

1
2
3
4
Collection<String> c = ...;
for (String string : c) {
//do someting with string
}

Iterator使用方法

  • next()
    java迭代器Iterator处于两个元素之间
    当调用next时候,迭代器就跳过元素,返回刚刚元素的引用

    迭代器向前移动
    迭代器向前移动
  • remove()
    删除一个元素,是删除上一次next返回的元素(当前位置左边元素)
    remove和next具有相互依赖型,如果没有调用next,使用remove是非法的,会抛出java.lang.IllegalStateException

    1
    2
    3
    4
    5
    6
    bIterator = b.iterator();
    bIterator.remove();
    bIterator.remove();//error
    bIterator.next();
    bIterator.remove();//right

AbstractCollection类

实现了Collection接口
设计上体现了接口与实现的分离,各个类可以实现自己的iterator和size,通用的Collection已经实现

1
2
3
4
5
6
7
public abstract class AbstractCollection<E> implements Collection<E> {
//iterator和size抽象化
public abstract Iterator<E> iterator();
public abstract int size();
//实现Collection中的方法
...
}