Java集合源码分析→ArrayList
来源:互联网 发布:淘宝客推广什么产品好 编辑:程序博客网 时间:2024/06/06 00:50
ArrayList简介
ArrayList是List接口的一个实现,是基于数组实现的,容量可以进行动态增加。ArrayList不是线程安全的,如果需要在多线程中使用推荐使用Collections.synchronizedList(List<T> list)
方法创建线程安全的List集合,或者使用concurrent包下的CopyOnWriteArrayList<>()
类创建线程安全的类
运行环境
- OS:Win7 64bit
- idea:IntelliJ IDEA 2017
- jdkVersion:1.7.0_79 64 bit
- 使用的pom.xml:无
ArrayList源码分析
package java.util;/** * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see LinkedList * @see Vector * @since 1.2 */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 = {}; /** * The array buffer into which the elements of the ArrayList are stored. * ArrayList存储在该数组中,容量就是数组的大小。任何空的ArrayList的elementData和EMPTY_ELEMENTDATA相等。 * 当添加第一个元素的时候容量扩展为DEFAULT_CAPACITY */ private transient Object[] elementData; /** * ArrayList的size,这个数字是ArrayList的内容个数 * @serial */ private int size; /** * 该构造方法创建一个空的list初始化容量是由参数指定的 * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * Constructs an empty list with an initial capacity of ten. 这是1.6版本的注释, * 现在这个版本默认创建后是0长度的数组,第一次添加时才初始化容量 * 空的构造方法,默认是空的数组 */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 这是1.6版本的空构造方法 * */ public ArrayList() { this(10); } /** *构造一个包含指定集合的元素的列表,按照它们由集合的迭代器返回的顺序。 * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ 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); } /** * 将集合的数组长度变成和集合size */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } } /** * 添加集合的容量,确保增加指定参数的最小容量。其实也就是先往小的加 */ 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; //如果list集合为空返回默认的大小 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); } /** * 数组最大能分配的值 * 一些虚拟机保留了一些头信息 * 尝试分配一些大的数组可能的结果是OutOfMemoryError,请求数组的size超过了VM限制 */ 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; } /** * 返回该list的元素个数 * @return the number of elements in this list */ public int size() { return size; } /** * 如果该list不包含任何元素则返回true * @return <tt>true</tt> if this list contains no elements */ public boolean isEmpty() { return size == 0; } /** * 如果该list包含指定的元素则返回true */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 返回的第一个匹配指定元素的索引,如果返回-1表示这个list集合没有包含该元素。 * 更加准确的说是返回匹配的最小的索引,从0开始到size进行循环 */ 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; } /** * 反向查询元素,如果返回-1表示这个list集合没有包含该元素。 * 更加准确的说是返回匹配的最大的索引,从size开始到0进行循环 */ 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; } /** * 复制集合 * @return a clone of this <tt>ArrayList</tt> instance */ 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(); } } /** * 将集合转换成数组,该数组包含集合的所有元素。该数组的元素顺序和list集合一致 * 该方法会新创建一个数组实例 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 将集合转换成数组返回 */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // 如果传入的数组长度小于size则会新建一个array,该array的长度等于集合的size return (T[]) Arrays.copyOf(elementData, size, a.getClass()); //否则还是使用传入的数组,并将集合元素复制到数组中 System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) //将传入数组索引为集合size的值置为null a[size] = null; return a; } // 数组随机访问 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** * 返回指定索引元素 */ public E get(int index) { rangeCheck(index); return elementData(index); } /** * 替换指定索引元素,并返回被替换的元素 */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * 追加指定的元素到集合的末尾,第一次添加的时候会指定数组的默认length。 * 这个和1.6版本不同 */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * 在集合的指定位置添加元素 */ public void add(int index, E element) { rangeCheckForAdd(index); //校验给定索引的合法性 ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index);//这里涉及到数组的复制,这就导致ArrayList随机添加消耗很大。 //如果index较小,size很大。则需要复制的元素是size-index elementData[index] = element;//将指定元素添加到指定索引 size++; } /** * 移除一个元素,如果这个元素不是最后还涉及元素移动的操作 */ public E remove(int index) { rangeCheck(index);//校验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; } /** * 这个和索引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; } /* * 参考remove(int index)方法 */ 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 } /** * 清除集合中的所有元素 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 添加指定的集合到该ArrayList的的最后,如果有其他线程修改了入参, * 将不会影响该方法的操作 */ 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; } /** * 参考addAll(Collection<? extends E> c)方法,该方法增加了元素的移动 */ 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; } /** * 移除给定范围内的数据 */ 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; } /** * 移除给定集合包含的元素 */ 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; }}
对ArrayList的总结
ArrayList底层是使用数组实现的,随机访问效率高,随机删除和动态扩容效率低
无参构造方法和jdk1.6不一样,初始化后是不会马上分配数组的大小的,而是在第一次add的时候进行分配
- 在随机删除和随机添加时涉及到内存移动比较耗时,数组length扩容的时候也涉及内存复制。效率不高
- ArrayList扩容时设置新的容量为旧容量的1.5倍加1,如果设置的新容量不够,则直接将新容量设置为传入的参数
阅读全文
2 0
- Java集合源码分析→ArrayList
- Java集合-ArrayList源码分析
- 【java集合】ArrayList源码分析
- java 集合ArrayList及LinkList源码分析
- Java集合框架源码分析之ArrayList
- java 集合ArrayList及LinkList源码分析
- 从源码分析java集合【ArrayList】
- Java集合系列之ArrayList源码分析
- java 集合ArrayList及LinkList源码分析
- java集合03--ArrayList源码分析
- java集合03--ArrayList源码分析
- Java集合源码分析之ArrayList
- java 集合ArrayList及LinkList源码分析
- java集合类源码分析 ArrayList
- Java集合-ArrayList源码分析及注意事项
- java集合(2):ArrayList源码分析
- java集合-ArrayList和源码分析
- Java集合之ArrayList源码分析
- HDU
- SpringBoot 实战 (二) :web 综合应用(配置Servlet、Listener、Filter,Log)
- HDU_6154 CaoHaha's staff
- android 关于apk 打包后的地图定位和导航失败的问题
- 自定义标签实现按钮权限
- Java集合源码分析→ArrayList
- C++学习笔记系列四
- API生命周期第三阶段:API实施:使用swagger codegen生成可部署工程,择取一个作为mock service
- nyoj 49开心的小明
- present or future: optimal pricing for spot instances文章阅读笔记
- 原理总结-spring
- mysql用navicat导入sql文件报错问题
- 实用的快速获取控件属性的分类 UIView+FGFrame
- 反转单链表问题