各种关系
浅蓝色是接口
深蓝色是类
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使用方法
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中的方法 ... }
|