Collection是一个接口,它主要的两个分支是List和Set。如下图所示:
![](https://img-blog.csdn.net/20160408221840040?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
List和Set都是接口,它们继承与Collection。List是有序的队列,可以用重复的元素;而Set是数学概念中的集合,不能有重复的元素。List和Set都有它们各自的实现类。
为了方便,我们抽象出AbstractCollection类来让其他类继承,该类实现类Collection中的绝大部分方法。AbstractList和AbstractSet都继承与AbstractCollection,具体的List实现类继承与AbstractList,而Set的实现类则继承与AbstractSet。
另外,Collection中有个iterator()方法,它的作用是返回一个Iterator接口。通常,我们通过Iterator迭代器来遍历集合。ListIterator是List接口所特有的,在List接口中,通过ListIterator()返回一个ListIterator对象。
我们首先来阅读下这些 接口和抽象类以及他们的实现类中都有哪些方法:
1. Collection
Collection的定义如下:
- public interface Collection<E> extends Iterable<E> {}
从它的定义中可以看出,Collection是一个接口。它是一个高度抽象出来的集合,包含了集合的基本操作:添加、删除、清空、遍历、是否为空、获取大小等。 Collection接口的所有子类(直接子类和简介子类)都必须实现2种构造函数:不带参数的构造函数和参数为Collection的构造函数。带参数的构造函数可以用来转换Collection的类型。下面是Collection接口中定义的API:
-
- abstract boolean add(E object)
- abstract boolean addAll(Collection<? extends E> collection)
- abstract void clear()
- abstract boolean contains(Object object)
- abstract boolean containsAll(Collection<?> collection)
- abstract boolean equals(Object object)
- abstract int hashCode()
- abstract boolean isEmpty()
- abstract Iterator<E> iterator()
- abstract boolean remove(Object object)
- abstract boolean removeAll(Collection<?> collection)
- abstract boolean retainAll(Collection<?> collection)
- abstract int size()
- abstract <T> T[] toArray(T[] array)
- abstract Object[] toArray()
2. List
List的定义如下:
- public interface List<E> extends Collection<E> {}
从List定义中可以看出,它继承与Collection接口,即List是集合的一种。List是有序的队列,List中的每一个元素都有一个索引,第一个元素的索引值为0,往后的元素的索引值依次+1.,List中允许有重复的元素。 List继承Collection自然包含了Collection的所有接口,由于List是有序队列,所以它也有自己额外的API接口。API如下:
-
- abstract boolean add(E object)
- abstract boolean addAll(Collection<? extends E> collection)
- abstract void clear()
- abstract boolean contains(Object object)
- abstract boolean containsAll(Collection<?> collection)
- abstract boolean equals(Object object)
- abstract int hashCode()
- abstract boolean isEmpty()
- abstract Iterator<E> iterator()
- abstract boolean remove(Object object)
- abstract boolean removeAll(Collection<?> collection)
- abstract boolean retainAll(Collection<?> collection)
- abstract int size()
- abstract <T> T[] toArray(T[] array)
- abstract Object[] toArray()
-
- abstract void add(int location, E object)
- abstract boolean addAll(int location, Collection<? extends E> collection)
- abstract E get(int location)
- abstract int indexOf(Object object)
- abstract int lastIndexOf(Object object)
- abstract ListIterator<E> listIterator(int location)
- abstract ListIterator<E> listIterator()
- abstract E remove(int location)
- abstract E set(int location, E object)
- abstract List<E> subList(int start, int end)
3. Set
Set的定义如下:
- public interface Set<E> extends Collection<E> {}
Set也继承与Collection接口,且里面不能有重复元素。关于API,Set与Collection的API完全一样,不在赘述。 4. AbstractCollection
- public abstract class AbstractCollection<E> implements Collection<E> {}
AbstractCollection是一个抽象类,它实现了Collection中除了iterator()和size()之外的所有方法。AbstractCollection的主要作用是方便其他类实现Collection.,比如ArrayList、LinkedList等。它们想要实现Collection接口,通过集成AbstractCollection就已经实现大部分方法了,再实现一下iterator()和size()即可。
下面看一下AbstractCollection实现的部分方法的源码:
- public abstract class AbstractCollection<E> implements Collection<E> {
- protected AbstractCollection() {
- }
-
- public abstract Iterator<E> iterator();
-
- public abstract int size();
-
- public boolean isEmpty() {
- return size() == 0;
- }
-
- 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;
- }
-
- public Object[] toArray() {
-
- Object[] r = new Object[size()];
- Iterator<E> it = iterator();
- for (int i = 0; i < r.length; i++) {
- if (! it.hasNext())
-
- return Arrays.copyOf(r, i);
- r[i] = it.next();
- }
- return it.hasNext() ? finishToArray(r, it) : r;
- }
-
- public <T> T[] toArray(T[] a) {
-
- int size = size();
- T[] r = a.length >= size ? a :
- (T[])java.lang.reflect.Array
- .newInstance(a.getClass().getComponentType(), size);
- Iterator<E> it = iterator();
-
- for (int i = 0; i < r.length; i++) {
- if (! it.hasNext()) {
- if (a == r) {
- r[i] = null;
- } else if (a.length < i) {
- return Arrays.copyOf(r, i);
- } else {
- System.arraycopy(r, 0, a, 0, i);
- if (a.length > i) {
- a[i] = null;
- }
- }
- return a;
- }
- r[i] = (T)it.next();
- }
-
- return it.hasNext() ? finishToArray(r, it) : r;
- }
-
- private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
- int i = r.length;
- while (it.hasNext()) {
- int cap = r.length;
- if (i == cap) {
- int newCap = cap + (cap >> 1) + 1;
-
- if (newCap - MAX_ARRAY_SIZE > 0)
- newCap = hugeCapacity(cap + 1);
- r = Arrays.copyOf(r, newCap);
- }
- r[i++] = (T)it.next();
- }
-
- return (i == r.length) ? r : Arrays.copyOf(r, i);
- }
-
- private static int hugeCapacity(int minCapacity) {
- if (minCapacity < 0)
- throw new OutOfMemoryError
- ("Required array size too large");
- return (minCapacity > MAX_ARRAY_SIZE) ?
- Integer.MAX_VALUE :
- MAX_ARRAY_SIZE;
- }
-
-
- 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;
- }
- <pre name="code" class="java">
- public boolean containsAll(Collection<?> c) {
- for (Object e : c)
- if (!contains(e))
- return false;
- return true;
- }
-
-
- public boolean addAll(Collection<? extends E> c) {
- boolean modified = false;
- for (E e : c)
- if (add(e))
- modified = true;
- return modified;
- }
-
-
- public boolean removeAll(Collection<?> c) {
- boolean modified = false;
- Iterator<?> it = iterator();
- while (it.hasNext()) {
- if (c.contains(it.next())) {
- it.remove();
- modified = true;
- }
- }
- return modified;
- }
-
-
- public void clear() {
- Iterator<E> it = iterator();
- while (it.hasNext()) {
- it.next();
- it.remove();
- }
- }
-
-
- 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(' ');
- }
- }
-
- }
5. AbstractList
AbstractList的定义如下:
- public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {}
从定义中可以看出,AbstractList是一个继承AbstractCollection,并且实现了List接口的抽象类。它实现了List中除了size()、get(int location)之外的方法。 AbstractList的主要作用:它实现了List接口中的大部分函数,从而方便其它类继承List。另外,和AbstractCollection相比,AbstractList抽象类中,实现了iterator()方法。
AbstractList抽象类的源码如下:
- public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
-
- protected AbstractList() {
- }
-
- public boolean add(E e) {
- add(size(), e);
- return true;
- }
-
- abstract public E get(int index);
-
- public E set(int index, E element) {
- throw new UnsupportedOperationException();
- }
-
- public void add(int index, E element) {
- throw new UnsupportedOperationException();
- }
-
- public E remove(int index) {
- throw new UnsupportedOperationException();
- }
-
-
- public int indexOf(Object o) {
- ListIterator<E> it = listIterator();
- if (o==null) {
- while (it.hasNext())
- if (it.next()==null)
- return it.previousIndex();
- } else {
- while (it.hasNext())
- if (o.equals(it.next()))
- return it.previousIndex();
- }
- return -1;
- }
-
- public int lastIndexOf(Object o) {
- ListIterator<E> it = listIterator(size());
- if (o==null) {
- while (it.hasPrevious())
- if (it.previous()==null)
- return it.nextIndex();
- } else {
- while (it.hasPrevious())
- if (o.equals(it.previous()))
- return it.nextIndex();
- }
- return -1;
- }
-
-
-
- public void clear() {
- removeRange(0, size());
- }
-
- public boolean addAll(int index, Collection<? extends E> c) {
- rangeCheckForAdd(index);
- boolean modified = false;
- for (E e : c) {
- add(index++, e);
- modified = true;
- }
- return modified;
- }
-
- protected void removeRange(int fromIndex, int toIndex) {
- ListIterator<E> it = listIterator(fromIndex);
- for (int i=0, n=toIndex-fromIndex; i<n; i++) {
- it.next();
- it.remove();
- }
- }
-
-
-
- public Iterator<E> iterator() {
- return new Itr();
- }
-
- public ListIterator<E> listIterator() {
- return listIterator(0);
- }
-
- public ListIterator<E> listIterator(final int index) {
- rangeCheckForAdd(index);
-
- return new ListItr(index);
- }
-
- private class Itr implements Iterator<E> {
- int cursor = 0;
- int lastRet = -1;
-
-
-
-
-
- int expectedModCount = modCount;
-
- public boolean hasNext() {
- return cursor != size();
- }
-
- public E next() {
- checkForComodification();
- try {
- int i = cursor;
- E next = get(i);
- lastRet = i;
- cursor = i + 1;
- return next;
- } catch (IndexOutOfBoundsException e) {
- checkForComodification();
- throw new NoSuchElementException();
- }
- }
-
- public void remove() {
- if (lastRet < 0)
- throw new IllegalStateException();
- checkForComodification();
-
- try {
- AbstractList.this.remove(lastRet);
- if (lastRet < cursor)
- cursor--;
- lastRet = -1;
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException e) {
- throw new ConcurrentModificationException();
- }
- }
-
- final void checkForComodification() {
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- }
- }
-
- private class ListItr extends Itr implements ListIterator<E> {
- ListItr(int index) {
- cursor = index;
- }
-
- public boolean hasPrevious() {
- return cursor != 0;
- }
-
- public E previous() {
- checkForComodification();
- try {
- int i = cursor - 1;
- E previous = get(i);
- lastRet = cursor = i;
- return previous;
- } catch (IndexOutOfBoundsException e) {
- checkForComodification();
- throw new NoSuchElementException();
- }
- }
-
- public int nextIndex() {
- return cursor;
- }
-
- public int previousIndex() {
- return cursor-1;
- }
-
- public void set(E e) {
- if (lastRet < 0)
- throw new IllegalStateException();
- checkForComodification();
-
- try {
- AbstractList.this.set(lastRet, e);
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException ex) {
- throw new ConcurrentModificationException();
- }
- }
-
- public void add(E e) {
- checkForComodification();
-
- try {
- int i = cursor;
- AbstractList.this.add(i, e);
- lastRet = -1;
- cursor = i + 1;
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException ex) {
- throw new ConcurrentModificationException();
- }
- }
- }
-
-
-
- public List<E> subList(int fromIndex, int toIndex) {
- return (this instanceof RandomAccess ?
- new RandomAccessSubList<>(this, fromIndex, toIndex) :
- new SubList<>(this, fromIndex, toIndex));
- }
-
-
- public boolean equals(Object o) {
- if (o == this)
- return true;
- if (!(o instanceof List))
- return false;
-
- ListIterator<E> e1 = listIterator();
- ListIterator e2 = ((List) o).listIterator();
- while (e1.hasNext() && e2.hasNext()) {
- E o1 = e1.next();
- Object o2 = e2.next();
- if (!(o1==null ? o2==null : o1.equals(o2)))
- return false;
- }
- return !(e1.hasNext() || e2.hasNext());
- }
-
- public int hashCode() {
- int hashCode = 1;
- for (E e : this)
- hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
- return hashCode;
- }
-
- protected transient int modCount = 0;
-
- private void rangeCheckForAdd(int index) {
- if (index < 0 || index > size())
- throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
- }
-
- private String outOfBoundsMsg(int index) {
- return "Index: "+index+", Size: "+size();
- }
- }
-
- class SubList<E> extends AbstractList<E> {
- private final AbstractList<E> l;
- private final int offset;
- private int size;
-
-
-
- SubList(AbstractList<E> list, int fromIndex, int toIndex) {
- if (fromIndex < 0)
- throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
- if (toIndex > list.size())
- throw new IndexOutOfBoundsException("toIndex = " + toIndex);
- if (fromIndex > toIndex)
- throw new IllegalArgumentException("fromIndex(" + fromIndex +
- ") > toIndex(" + toIndex + ")");
- l = list;
- offset = fromIndex;
- size = toIndex - fromIndex;
- this.modCount = l.modCount;
- }
-
- public E set(int index, E element) {
- rangeCheck(index);
- checkForComodification();
- return l.set(index+offset, element);
- }
-
- public E get(int index) {
- rangeCheck(index);
- checkForComodification();
- return l.get(index+offset);
- }
-
- public int size() {
- checkForComodification();
- return size;
- }
-
- public void add(int index, E element) {
- rangeCheckForAdd(index);
- checkForComodification();
- l.add(index+offset, element);
- this.modCount = l.modCount;
- size++;
- }
-
- public E remove(int index) {
- rangeCheck(index);
- checkForComodification();
- E result = l.remove(index+offset);
- this.modCount = l.modCount;
- size--;
- return result;
- }
-
- protected void removeRange(int fromIndex, int toIndex) {
- checkForComodification();
- l.removeRange(fromIndex+offset, toIndex+offset);
- this.modCount = l.modCount;
- size -= (toIndex-fromIndex);
- }
-
- public boolean addAll(Collection<? extends E> c) {
- return addAll(size, c);
- }
-
- public boolean addAll(int index, Collection<? extends E> c) {
- rangeCheckForAdd(index);
- int cSize = c.size();
- if (cSize==0)
- return false;
-
- checkForComodification();
- l.addAll(offset+index, c);
- this.modCount = l.modCount;
- size += cSize;
- return true;
- }
-
- public Iterator<E> iterator() {
- return listIterator();
- }
-
- public ListIterator<E> listIterator(final int index) {
- checkForComodification();
- rangeCheckForAdd(index);
-
- return new ListIterator<E>() {
- private final ListIterator<E> i = l.listIterator(index+offset);
-
- public boolean hasNext() {
- return nextIndex() < size;
- }
-
- public E next() {
- if (hasNext())
- return i.next();
- else
- throw new NoSuchElementException();
- }
-
- public boolean hasPrevious() {
- return previousIndex() >= 0;
- }
-
- public E previous() {
- if (hasPrevious())
- return i.previous();
- else
- throw new NoSuchElementException();
- }
-
- public int nextIndex() {
- return i.nextIndex() - offset;
- }
-
- public int previousIndex() {
- return i.previousIndex() - offset;
- }
-
- public void remove() {
- i.remove();
- SubList.this.modCount = l.modCount;
- size--;
- }
-
- public void set(E e) {
- i.set(e);
- }
-
- public void add(E e) {
- i.add(e);
- SubList.this.modCount = l.modCount;
- size++;
- }
- };
- }
-
- public List<E> subList(int fromIndex, int toIndex) {
- return new SubList<>(this, fromIndex, toIndex);
- }
-
- private void rangeCheck(int index) {
- if (index < 0 || index >= size)
- throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
- }
-
- private void rangeCheckForAdd(int index) {
- if (index < 0 || index > size)
- throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
- }
-
- private String outOfBoundsMsg(int index) {
- return "Index: "+index+", Size: "+size;
- }
-
- private void checkForComodification() {
- if (this.modCount != l.modCount)
- throw new ConcurrentModificationException();
- }
- }
-
- class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
- RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
- super(list, fromIndex, toIndex);
- }
-
- public List<E> subList(int fromIndex, int toIndex) {
- return new RandomAccessSubList<>(this, fromIndex, toIndex);
- }
- }
6. AbstractSet
AbstractSet的定义如下:
- public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {}
AbstractSet是一个继承与AbstractCollection,并且实现了Set接口的抽象类。由于Set接口和Collection接口中的API完全一样,所以Set也就没有自己单独的API。和AbstractCollection一样,它实现了List中除iterator()和size()外的方法。所以源码和AbstractCollection的一样。 AbstractSet的主要作用:它实现了Set接口总的大部分函数,从而方便其他类实现Set接口。 7. Iterator
Iterator的定义如下:
- public interface Iterator<E> {}
Iterator是一个接口,它是集合的迭代器。集合可以通过Iterator去遍历其中的元素。Iterator提供的API接口包括:是否存在下一个元素,获取下一个元素和删除当前元素。 注意:Iterator遍历Collection时,是fail-fast机制的。即,当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了,那么线程A访问集合时,就会抛出CurrentModificationException异常,产生fail-fast事件。下面是Iterator的几个API。
-
- abstract boolean hasNext()
- abstract E next()
- abstract void remove()
8. ListIterator
ListIterator的定义如下:
- public interface ListIterator<E> extends Iterator<E> {}
ListIterator是一个继承Iterator的接口,它是队列迭代器。专门用于遍历List,能提供向前和向后遍历。相比于Iterator,它新增了添加、是否存在上一个元素、获取上一个元素等API接口:
-
- abstract boolean hasNext()
- abstract E next()
- abstract void remove()
-
- abstract void add(E object)
- abstract boolean hasPrevious()
- abstract int nextIndex()
- abstract E previous()
- abstract int previousIndex()
- abstract void set(E object)
Collection的架构就讨论到这吧,如果有问题欢迎留言指正~
转载:http://blog.csdn.net/eson_15/article/details/51139978