依然延续之前StringBuilder和StringBuffer源码分析的行文思路,首先从整体上了解java集合框架,下面就是一幅java集合框架图。
从图中可以看到,ArrayList处在这棵继承树的最底部,也就是一个叶子结点,我们要想分析ArrayList的实现逻辑,必然少不了去研究的它的超类。那么下面我们就从Collection开始,自顶向下进行分析。
public interface Collection<E> extends Iterable<E> {
// Query Operations 查询操作
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
// Modification Operations 修改操作
boolean add(E e);
boolean remove(Object o);
// Bulk Operations 批量操作
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing 比较以及hash
boolean equals(Object o);
int hashCode();
}
package java.lang;
import java.util.Iterator;
public interface Iterable<T> {
Iterator<T> iterator();
}
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
public interface List<E> extends Collection<E> {
// Query Operations
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
// Modification Operations
boolean add(E e);
boolean remove(Object o);
// Bulk Modification Operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing
boolean equals(Object o);
int hashCode();
// Positional Access Operations
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
// Search Operations
int indexOf(Object o);
int lastIndexOf(Object o);
// List Iterators
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// View
List<E> subList(int fromIndex, int toIndex);
}
public interface ListIterator<E> extends Iterator<E> {
// Query Operations
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
// Modification Operations
void remove();
void set(E e);
void add(E e);
}
public abstract Iterator<E> iterator(); public abstract int size();
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 boolean add(E e) {
throw new UnsupportedOperationException();
}
int cursor = 0;//游标,下一次调用next的位置 int lastRet = -1;//保存上一次next的位置 int expectedModCount = modCount;//集合被改变的次数再看下具体实现:
public boolean hasNext() {
return cursor != size();//判断游标是否等于集合大小,不是则返回true
}
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 static final long serialVersionUID = 8683452581122892189L; private transient Object[] elementData;//这即存放ArrayList元素的数组,可扩容。 private int size;//当前ArrayList的大小(实际元素数目)
public ArrayList(int initialCapacity) {//参数为初始容量
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {//默认容量是10
this(10);
}
public ArrayList(Collection<? extends E> c) {//从集合中构造
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}public void ensureCapacity(int minCapacity) {
if (minCapacity > 0)
ensureCapacityInternal(minCapacity);
}
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容为原来的1.5倍
if (newCapacity - minCapacity < 0)//如果还是比最小容量小,那么干脆
newCapacity = minCapacity;//就设置为minCapacity
if (newCapacity - MAX_ARRAY_SIZE > 0)//看是否超过了数组容量的最大值
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;//一目了然
return true;
}clear方法: public void clear() {
modCount++;//改变次数加1
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;//置空
size = 0;//size归0
}remove方法: public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
List<String> list = new ArrayList<String>();
list.add("zhangsan");
list.add("lisi");
list.add("wangwu");
//如果直接用向下转型的方法,将整个ArrayList集合转变为指定类型的Array数组,便会抛出ClassCast异常
String[] strs = (String[]) list.toArray();//错误!!!
for(int i = 0; i < strs.length; i++)
{
System.out.println(strs[i]);
}List<String> list = new ArrayList<String>();
ist.add("zhangsan");
list.add("lisi");
list.add("wangwu");
Object[] strs = (Object[]) list.toArray();
for(int i = 0; i < strs.length; i++)
{
System.out.println((String)strs[i]);
}List<String> list = new ArrayList<String>();
list.add("zhangsan");
list.add("lisi");
list.add("wangwu");
String[] strs = list.toArray(new String[list.size()]);
for(int i = 0; i < strs.length; i++)
{
System.out.println(strs[i]);
}
【源码】ArrayList源码剖析,布布扣,bubuko.com
原文:http://blog.csdn.net/chdjj/article/details/38427219