java之ArrayList源码解析
2015-07-14 11:21
507 查看
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; //默认列表长度 private static final int DEFAULT_CAPACITY=10; //空列表被共享 private static final Object[] EMPTY_ELEMENTDATA = {}; //用来存储列表数据元素的数组 private transient Object[] elementData; //ArrayList当前存储数据长度 private int size; /** * 构造指定初始容量的列表数组 */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * 无参构造函数,指定默认为空的列表数组 */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 将集合元素初始化到列表数组中,并且指定长度为集合元素个数 */ 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); } /** * modCount是指定列表数组结构发生改变的次数 * trimToSize()将,释放列表数组中没有使用的空间,将数组长度指定为当前元素的个数,通过数组copy,只有确定数组不在添加元素在调用, * 负责每次copy数组效率非常低。 */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } } /** * ensureCapacity()用于容量自动扩充,首先判断调用ensureCapacity()方法的是否是创建初始数组,如果是有可能没有指定初始容量,则将初始容量 * 指定为10,如果指定了初始容量大于10,则根据指定的初始容量进行扩容。 * 如果是非空列表数组调用ensureCapacity()则对其进行扩容(将其赋为0就是确保肯定能够扩容),根据指定多的大小调用ensureExplicitCapacity()方法进行扩容 * ensureExplicitCapacity确保确保指定的容量大于当前数组存储元素的个数,然后调用grow()进行扩容,扩容容量增加为原来的二倍,如果传递的指定的minCapacity容量 * 比其二倍还要多,则使用指定大小的容量,如果扩容之后的容量大于int类型能够表示的大小,则直接将其大小赋值为Integer.MAX_VALUE */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != EMPTY_ELEMENTDATA) // any size if real element table ? 0 // larger than default for empty table. It's already supposed to be // at default size. : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = 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; } /** * 返回当前存储数据元素的个数 */ public int size() { return size; } /** * 判断其当前为数组是否为空,就是判断当前元素个数是否为0 */ public boolean isEmpty() { return size == 0; } /** * 指定元素是否包含在数组中,是通过indexOf()方法进行判断,指定元素位置的,如果不存在返回-1 */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 判断指定对象是否在数组当中,其返回的是首次出现该元素的位置,indexOf()会首先判断传递的元素是否为null,如果是和null进行比较 * 否则使用o.equals(elementData[i])和元素进行比较,如果没有找到则返回-1,找到返回其出现的下标位置 */ public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } /** * lastIndexOf(Object o)通过反向进行查找,查找该元素最后一次出现在列表的位置,判断原理和IndexOf()一样,只不过for循环反向遍历 */ public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** * 通过轻复制进行列表克隆 */ public Object clone() { try { @SuppressWarnings("unchecked") ArrayList<E> v = (ArrayList<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** * 将列表转换称数组,其实就是进行元素复制,复制返回一个数组对象 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 指定要转换的数组,如果这个数组容量不足,则返回一个新的数组,否则就将列表元素复制到这个数组当中 */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } /** * 通过elementData返回指定位置的数组元素 */ @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** * get获取指定位置的元素,其实调用elementData方法,就是直接取出数组特定索引的元素 * 首先会进行判断指定位置是否有可能超过数组长度 */ public E get(int index) { rangeCheck(index); return elementData(index); } /** * 通过set更改指定位置元素的值,返回原先值 */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * 列表元素添加,首先通过ensureCapacityInternal判断是否需要扩容,是通过当前元素个数加上要添加的元素与当前数组长度进行比较,即minCapacity - elementData.length * 如果大于当前数组长度,则进行扩容,然后在列表最后添加元素 */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * 在指定位置添加元素,也会判断位置,容量。 * 然后将指定位置之后的元素全体向后移动一个位置,然后在指定位置添加元素,这个算法时间复杂度O(n),应尽量少使用 */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } /** * 删除指定位置元素,首先判断位置,取出要删除的值作为方法的返回值。然后将指定位置后的元素全体向前移动一位,然后长度当前元素个数减1,最后位置复制null */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; } /** * 删除指定元素,还是首先进行判断要删除的值是否为null,决定和什么进行比较。 * 找到指定元素后调用fastRemove()方法,将当前索引下标传递过去,然后就和删除指定位置元素一样了 */ 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; // clear to let GC do its work } /** * 清空数组列表,将其全部赋值为null,然后长度设置为0 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 将指定集合元素添加到列表末尾,首先根据集合长度也要判断数组列表是否需要进行扩容,然后将集合元素copy到列表末尾,再将元素个数加上 * 集合元素个数 */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } /** * 指定位置添加集合中全部元素,首先要为集合元素空出位置,将列表中index后元素全体向后移动集合个数的长度,然后将集合中元素添加到列表当中 */ public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * 删除指定区间元素,将区间toindex后的全体元素向前移动删除区间长度的单位,然后将列表中移动之后的位置元素设置为null,列表元素个数 * 为原列表元素个数减去删除的元素个数 */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // clear to let GC do its work int newSize = size - (toIndex-fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } /** * 删除列表中包含指定集合中的元素,removeAll通过调用batchRemove()方法,barchRemove通过传递一个boolean值确定是retainAll * 调用还是removeAll调用,retainAll是将不包含在集合中的元素在列表中删除 */ public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } public boolean retainAll(Collection<?> c) { return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } /** * 返回ListIterator实例,可以进行ListIterator迭代操作,从指定位置开始进行迭代 */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * 从从列表其实位置进行迭代 */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * 返回Iterator迭代器 */ public Iterator<E> iterator() { return new Itr(); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 从源码安装Mysql/Percona 5.5
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树