jdk源码学习笔记---ArrayList
来源:互联网 发布:苹果cms手机模板免费 编辑:程序博客网 时间:2024/06/11 10:43
初衷
刚接触java不到2礼拜的小白试图通过阅读jdk的源码来学习java。如有理解或表达不对的地方,欢迎各位大佬指正,谢谢。
1. ArrayList类简介
ArrayList是一个数组序列,相当于一个动态数组。与Java中的数组相比,它的容量能动态的增长。并提供了一些列对外开放的接口供调用方维护这个数组序列中的数据。
ArrayList类的继承和实现体系如下图所示:
ArrayList继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。
ArrayList 继承了AbstractList,实现了List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。
ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。稍后,我们会比较List的“快速随机访问”和“通过Iterator迭代器访问”的效率。
ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
和Vector不同,ArrayList中的操作不是线程安全的!所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector或者CopyOnWriteArrayList。
2. elementData
elementData数组是ArrayList的真正维护的数据,定义如下:
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access
值得注意的是elementData使用transient( transient用来表示一个域不是该对象序行化的一部分,当一个对象被序行化的时候,transient修饰的变量的值是不包括在序行化的表示中的。)关键字来修饰的。这是因为elementData一般会有一些预留的容量,当容量不够时会自动扩充容量。也就是说预留的空间中是没有实际数据的。用transient关键字来修饰elementData可以只序列化elementData中实际存储的数据,从而节省空间和时间。
3. 构造函数
3.1 public ArrayList(int initialCapacity)
根据initialCapacity来为elementData数组预留空间,代码如下:
public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }private static final Object[] EMPTY_ELEMENTDATA = {};
3.2 public ArrayList()
为elementData分配默认的容量,默认的容量是10,代码如下:
public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
3.3 public ArrayList(Collection
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
这里值得注意的有两点,第1点是在拷贝数据之前检查c中的数据是不是Object类型的数据。这是因为各种Collection的toArray方法的实现都不同,ArrayList的toArray返回的是Object[],而其他的就可能不是,例如Arrays.asList(“1”).toArrary()这个返回的是String[]。第2点是如果elementData的类型不是Object类型,那么elementData需要从堆中拷贝过来,而不是直接引用堆中的数据。这是因为如果c中的数据被修改了,那么此时的elementData也会随着修改。
4. 增
对于增这个操作来说,ArrayList提供了Add方法,该方法有两个重载的版本,分别为add(E e)和add(int index, E element)。下面来分别分析ArrayList在增时做了哪些事。
4.1 public boolean add(E e)
这个方法用于在ArrayList的末尾添加一个元素,代码如下:
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
可以看出在往elementData的末尾添加元素时,先要确定此时elementData的容量。ensureCapacityInternal就是用来计算添加元素的时候容量是否应该扩容的方法,其代码如下:
private void ensureCapacityInternal(int minCapacity) { //如果容量是默认容量则选两者中最大的为最小需求容量 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }private void ensureExplicitCapacity(int minCapacity) {//modCount是size发生变化的次数,也就是迭代器失效的次数 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); 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; }
从上面的代码能够看出ArrayList在扩容的时候会在原来的容量基础上加50%(除了一些特殊情况)。再确定完新的容量之后,会在堆中再开辟一块内存,内存的大小为新容量的大小,并返回指向该内存的引用。
4.2 public void add(int index, E element)
在index指定的位置插入一个元素。过程很简单,先检查边界,然后计算add后应该有的容量,然后把从index位置开始到结尾的所有数据copy到index+1位起点的位置上,最后把index指定的位置的元素修改为element,并size+1。代码如下:
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++; }
4.3 public boolean addAll(Collection
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; }
4.4 public boolean addAll(Collection
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; }
5. 删
5.1 public E remove(int index)
删除index指定的元素,并将删除掉的元素返回出去。过程也很简单,先检查边界,然后计算有多少个坑需要往前移动,然后copy覆盖掉原有的元素,最后把最末尾的元素置为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; }
5.2 public boolean remove(Object o)
从ArrayList里面找第一个与o相等的元素,并把它删掉。过程也很简单,和5.1的套路差不多,只不过没有进行边界检查和记录待删除的元素而已。代码如下:
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; } //相比remove,没有边界检查和oldElment 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 }
5.3 public void clear()
删除所有元素,并提醒虚拟机辣鸡回收。代码如下:
public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }
5.4 protected void removeRange(int fromIndex, int toIndex)
套路总是惊人的相似,总之先计算有多少坑要覆盖,然后后面的坑置null,提醒gc,代码如下:
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; }
5.5 public boolean removeAll(Collection
public boolean removeAll(Collection<?> c) { //c若为null则抛空指针异常 Objects.requireNonNull(c); return batchRemove(c, false); }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++) //如果是做减法则会将不被c包含的元素留下,如果是做交集则会将不被c包含的元素删除。 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; }
5.6 public boolean retainAll(Collection
public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); }
6. 改
6.1 public E set(int index, E element)
将下标为index的坑改成element,代码如下:
public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
PS:返回值是替换之前的数据。
7. 查
7.1 public int indexOf(Object o)
返回o在ArrayList中第一次出现的位置,没找到就返回-1,代码如下:
public int indexOf(Object o) { if (o == null) { //是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; }
7.2 public int lastIndexOf(Object o)
返回o在ArrayList中最后一次出现的位置,没找到就返回-1,代码如下:
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; }
7.3 E elementData(int index)
根据index获取实际存储的数据(没做边界检查)。代码如下:
E elementData(int index) { return (E) elementData[index]; }
7.4 public E get(int index)
在调用elementData方法之前进行了边界检查,代码如下:
public E get(int index) { rangeCheck(index); return elementData(index); }private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
7.5 public boolean contains(Object o)
用于判断o属不属于ArrayList的数据集中。判断方式很简单,就是调用indexOf方法,检查返回值是不是-1。代码如下:
public boolean contains(Object o) { return indexOf(o) >= 0; }
8. 迭代器
ArrayList内有两个迭代器内部类Itr和ListItr,Itr的功能是能够从前往后遍历和删除,ListItr的功能是能够双向遍历、修改、删除及添加元素。之所以会有迭代器这种东西,是因为迭代器是一种模式,它可以使得对于序列类型的数据结构的遍历行为与被遍历的对象分离,即我们无需关心该序列的底层结构是什么样子的。只要拿到这个对象,使用迭代器就可以遍历这个对象的内部,能够将客户端和数据进行解耦。
8.1 Itr
这个实现了Iterator接口,代码如下:
private class Itr implements Iterator<E> { 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(); } } //可以用lambda表达式进行遍历 @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> 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(); } //防止在用迭代器迭代时使用非迭代器提供的修改ArrayList数据的方法而导致的迭代器失效 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
这些代码中可以看到进场要判断modCount是否和expectedModCount相等,这是因为迭代器遍历时不能使用非迭代器提供的修改数据的方法来修改ArrayList的数据。
8.2 ListItr
这个类继承了Itr,实现了ListIterator接口,而ListIterator接口继承自Iterator接口,是对Itr的一个扩展。代码如下:
private class ListItr extends Itr implements ListIterator<E> { 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(); } } //删除和访问候机结点的操作在Itr中已经实现了,这里就不需要override了 }
8.3 对外提供迭代器实例
Itr和ListIterator这两种迭代器是私有的内部类,所以需要对外提供得到这两种迭代器的实例的方法,外部用户可以根据自己的需求得到一个迭代器来对ArrayList进行操作。代码如下:
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); } public Iterator<E> iterator() { return new Itr(); }
- jdk源码学习笔记---ArrayList
- JDK源码学习之ArrayList
- ArrayList源码学习笔记
- 【JDK源码】从JDK/ArrayList源码学习高质量代码
- JDK源码学习系列04----ArrayList
- JDK源码学习之Arraylist与LinkedList
- JDK源码-ArrayList源码
- ArrayList<E>源码学习笔记
- ArrayList部分源码学习笔记
- JDK ArrayList 删除源码
- ## JDK源码--ArrayList
- JDK源码阅读-ArrayList
- jdk源码分析--ArrayList
- jdk源码学习笔记---Integer
- jdk源码学习笔记---Character
- jdk源码学习笔记--LinkedList
- jdk源码学习笔记---Thread
- [Java]JDK源码学习(1)ArrayList和Vector
- eth0 eth0:1 eth0.1 的区别
- WebGL之旅(七)varying变量
- R实战:【绘图】基础部分
- HDU 1312 Red and Black(并查集或者BFS)
- Struts2与MVC基础入门
- jdk源码学习笔记---ArrayList
- org.hibernate.MappingException: Unknown entity: com.lzw.hibernate.helloworld.News 解决问题
- U-boot2016.05移植TQ2440之norflash移植
- ruby-rails笔记
- 韩信点兵-OJ
- BSP树
- 转:瓦片地图TiledMap
- DC
- shell 简单学习1