博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java.util.ArrayList源码分析
阅读量:5919 次
发布时间:2019-06-19

本文共 7390 字,大约阅读时间需要 24 分钟。

public class ArrayList
extends AbstractList
implements List
, RandomAccess, Cloneable, java.io.Serializable

可变数组大小的List实现,允许所有的元素,包括null。(该类可粗略地看作是Vector,除了它不是同步化的)

size、isEmpty、get、set、iterator和listIterator操作的运行时间是常量。add操作对于添加n个元素,需要O(n)的时间。其他的操作需要线性时间。

每个ArrayList对象有一个capacity变量,它总是比list的size大一点,当一个元素添加到ArrayList时,它的capacity会自动地增大,以保证足够大的数组来存放元素。

ArrayList不是线程安全的。

3个实例变量

//默认的容器大小private static final int DEFAULT_CAPACITY = 10;//空数组,用于表示一个空的ArrayListprivate static final Object[] EMPTY_ELEMENTDATA = {};//装元素的容器transient Object[] elementData;//ArrayList的大小private int size;

 

3个构造器

//指定容器大小的构造器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;}//通过Collection实例构造ArrayListpublic ArrayList(Collection
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);}

 

扩容方式

//确保容器大小,作为导出APIpublic 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);}//扩容的方式是原容量的1.5倍 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 Iterator
iterator() { return new Itr();}//普通的迭代器实现private class Itr implements Iterator
{ int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer
consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }}

 

//返回列表迭代器,index指定初始位置public ListIterator
listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index);}//返回列表迭代器,初始位置为0public ListIterator
listIterator() { return new ListItr(0);}//这是一个列表的迭代器,可以往前迭代,也可以往后迭代private class ListItr extends Itr implements ListIterator
{ ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }}

 

//返回一个子列表,对该子列表的操作会影响原链表,如subList(f,t).clear()会把原列表f到t之间的元素删除public List
subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex);}

转载于:https://www.cnblogs.com/13jhzeng/p/5805172.html

你可能感兴趣的文章
左手写代码,右手维护互联网世界和平
查看>>
iOS中 支付宝钱包详解/第三方支付
查看>>
error the @annotation pointcut expression is only supported at Java 5 compliance level or above
查看>>
如何反编译APK?
查看>>
Webwork 学习之路(二)前端OGNL试练
查看>>
命名空间“HaiChuang.AMAC”中不存在类型或命名空间名称“WCFClient”。是否缺少程序集引用?...
查看>>
为php配置java环境
查看>>
MySQL Meta 信息与 CREATE TABLE 的对应关系
查看>>
Resx 文件无效,未能加载 .RESX 文件中使用的类型
查看>>
IOS 封装静态库(.a文件)
查看>>
[C++] 用Xcode来写C++程序[5] 函数的重载与模板
查看>>
[J2MEQ&A]WTK初始化WMAClient报错XXX has no IP address的解释
查看>>
TOAD 导出数据
查看>>
Linux中daemon()函数的使用
查看>>
Mac上的软件使用介绍
查看>>
Fork/Join框架(四)异步运行任务
查看>>
中间件技术及双十一实践·稳定性平台篇
查看>>
大数据催生新兴职业 数据分析师成IT界“大熊猫”
查看>>
Uvaoj10054 - The Necklace
查看>>
[流媒体]实例解析MMS流媒体协议,下载LiveMediaVideo[3]
查看>>