本文是通过android中的代码来学习数据结构,在android的实现数据结构过程中,采用了java中的接口,抽象类。所以要想读懂源码请先了解一些接口,抽象类,设计模式等。具体相关知识,请看此博客:
1、ArrayList
从android studio中打开ArrayList 源码可看出ArrayList继承了AbstractList并实现了Cloneable, Serializable, RandomAccess三个接口。
1)、AbstractList是什么,中有什么,干了什么?
先上类图:
![这里写图片描述](https://img-blog.csdn.net/20160927083740634)
a)、 AbstractList是一个抽象类,
b)、AbstractList继承了 AbstractCollection ,并实现了List 接口。
c)、在AbstractList中封装了四个内部类SimpleListIterator,FullListIterator,SubAbstractListRandomAccess,SubAbstractList
一个私有属性modCount (计数器)
一. SimpleListIterator
SimpleListIterator中的实例由 AbstractList中的方法iterator()获取对象,
SimpleListIterator源码如下:
private class SimpleListIterator implements Iterator<E> {
//单向链表的数据结构
int pos = -1;
int expectedModCount;
int lastPosition = -1;
SimpleListIterator() {
expectedModCount = modCount;//容器中含有的数量
}
public boolean hasNext() {
//下标加一与容器的大小做比较,如果小于容器所有数据的数量则返回true.
return pos + 1 < size();
}
public E next() {
if (expectedModCount == modCount) {
try {
E result = get(pos + 1);
lastPosition = ++pos;
return result;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
throw new ConcurrentModificationException();
}
public void remove() {
if (this.lastPosition == -1) {
throw new IllegalStateException();
}
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
try {
AbstractList.this.remove(lastPosition);
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
expectedModCount = modCount;
if (pos == lastPosition) {
pos--;
}
lastPosition = -1;
}
}
说明:
- Iterator是个接口,在此接口中有public boolean hasNext();public E next(); public void remove();三个方法。由于SimpleListIterator 实现了Iterator接口,所以必须重写hasNext(),next(),remove()方法。
- SimpleListIterator 存在的意义在于封装了一个简单的迭代器,在此迭代器中封装了一些遍历容器的算法。
二、FullListIterator
FullListIterator是继承于SimpleListIterator ,同时实现了ListIterator接口,此类可以指定下标位置进行循环遍历容器中数据,
获取FullListIterator对象通过 AbstractList中listIterator(int location) 方法获取。
具体使用:
在AbstractList中lastIndexOf(Object object),indexOf(Object object),removeRange(int start, int end),中使用了FullListIterator的迭代器。lastIndexOf代码如下:
/**
* Returns a list iterator on the elements of this list. The elements are
* iterated in the same order as they occur in the list. The iteration
* starts at the specified location.
*
* @param location
* the index at which to start the iter