ArrayList
ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存。
ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。
以下分析的是JDK1.8的ArrayList源码,跟JDK1.7的区别还是蛮大的。
一、定义
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
从ArrayList\可以看出它是支持泛型的,它继承自AbstractList,实现了List、RandomAccess、Cloneable、Java.io.Serializable接口
AbstractList提供了List接口的默认实现(个别方法为抽象方法)
List接口定义了列表必须实现的方法
RandomAccess是一个标记接口,接口内没有定义任何内容,支持快速随机访问,实际上就是通过下标序号进行快速访问
实现了Cloneable接口的类,可以调用Object.clone方法返回该对象的浅拷贝
通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。序列化接口没有方法或字段,仅用于标识可序列化的语义
二、属性
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * 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 /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
ArrayList提供了2个私有属性,elementData和size;很容易理解,elementData存储ArrayList内的元素,size表示它包含的元素的数量(实际数量而非容量)
transient关键字的作用:在采用Java默认的序列化机制的时候,被该关键字修饰的属性不会被序列化。
三、构造方法
ArrayList提供了三个构造方法:
// 带容量参数的构造方法 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { // 创建一个空数组 this.elementData = EMPTY_ELEMENTDATA; } else { // 参数小于0,抛出异常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } // 默认无参构造方法,创建一个容量为10的数组 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } // 集合作为参数的构造方法,集合转化为Object[] // c为null throws NullPointerException public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray 不一定返回的是Object[] if (elementData.getClass() != Object[].class) // 数组复制到 elementData elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // c的长度为0,创建容量为0的数组 this.elementData = EMPTY_ELEMENTDATA; } }
第一个构造方法使用initialCapacity来初始化elementData数组的大小;
第二个构造方法创建一个空的容量为10的elementData数组;
第三个构造方法将提供的集合转成数组并给elementData(返回若不是Object[],则转换为Object[]);
四、方法详细介绍
1. 元素存储
关于ArrayList元素的存储,提供了5个方法:
public E set(int index, E element)public boolean add(E e)public void add(int index, E element)public boolean addAll(Collection<? extends E> c)public boolean addAll(int index, Collection<? extends E> c)
set方法,替换元素
// 用指定的元素替代此列表中指定位置上的元素,并返回以前位于该位置上的元素 public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } // 检验index是否在范围内,不校验index为负数的情况,index为负数由数组校验 private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } // 返回指定位置上的元素 E elementData(int index) { return (E) elementData[index]; } private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; }
add(E e)方法,尾部添加元素
// 添加元素到列表的尾部,并返回true public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!!(这注释还两感叹号) elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { // 若是默认容量为10,则minCapacity取minCapacity和DEFAULT_CAPACITY最大值 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } // 记录容量扩容次数(Fast Fail机制,多线程) protected transient int modCount = 0; private void ensureExplicitCapacity(int minCapacity) { // 扩容次数+1 modCount++; // 若需要的容量大于目前elementData的容量,则进行扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); } // ArrayList容量的最大值(为啥是这个值设定?) private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 扩容到指定容量(有溢出处理) private void grow(int minCapacity) { int oldCapacity = elementData.length; // oldCapacity >> 1相当于 oldCapacity / 2,则下面的就是扩容50% int newCapacity = oldCapacity + (oldCapacity >> 1); // 若扩容50%还没到minCapacity,则扩容minCapacity if (newCapacity - minCapacity < 0) newCapacity = minCapacity; // 扩容容量 大于最大容量(溢出处理) if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // 扩容容量elementData elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // 溢出处理 throw new OutOfMemoryError(); // 扩容的容量是否大于最大数组容量,是则返回整型最大值,否则返回最大数组容量 return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
add(int index, E element)方法,指定位置添加元素
public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! // index后面的元素往后下标+1并复制到elementData System.arraycopy(elementData, index, elementData, index + 1, size - index); // 参数element赋值给指定位置的elementData elementData[index] = element; // 数组实际长度+1 size++; } // 校验索引下标范围(不能大于数组实际大小以及小于0,是就抛出异常) // 方法用于 add 和 addAll private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
此方法是System类提供的native方法,用于copy数组所用
src:源数组; srcPos:源数组要复制的起始位置; dest:目的数组; destPos:目的数组放置的起始位置; length:复制的长度
此方法的功能就是把dest从destPos到destPos+length的元素用src数组的srcPos位置开始替换
arraycopy调用了系统的C/C++代码,在JDK中是看不到的,但在openJDK中可以看到其源码。该函数实际上最终调用了C语言的memmove()函数,因此它可以保证同一个数组内元素的正确复制和移动,比一般的复制方法的实现效率要高很多,很适合用来批量处理数组。Java强烈推荐在复制大量数组元素时用该方法,以取得更高的效率。
```JAVA
public class ArrayCopyTest {
public static void main(String[] args) { char[] c1 = new String("123456").toCharArray(); char[] c2 = new String("abcdef").toCharArray(); System.arraycopy(c1,2 , c2, 1, 2); for(char c : c1){ System.out.print(c); } System.out.println(); for(char c : c2){ System.out.print(c); } }
}
```
结果为:
123456
a34def
addAll(Collection<? extends E> c)方法,尾部按顺序添加所有集合元素
// c为null 会抛出NullPointerException 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);// 数组copy size += numNew;// elementData实际大小size增加 return numNew != 0;// 返回是否有新元素添加 }
addAll(int index, Collection<? extends E> c)方法,指定位置按顺序添加所有集合元素
// c为null 会抛出NullPointerException 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; // elementData数组index后面的元素移动到elementData的末端 if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); // 添加的集合c中的所有元素index到index+numNewcopy进来 System.arraycopy(a, 0, elementData, index, numNew); size += numNew;// elementData实际大小size增加 return numNew != 0;// 返回是否有新元素添加 }
2. 元素读取
// 返回数组index所在的元素 public E get(int index) { rangeCheck(index);// 校验index是否越界 return elementData(index); } // 检验index是否在范围内,不校验index为负数的情况,index为负数由数组校验 private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } // 返回指定位置上的元素 E elementData(int index) { return (E) elementData[index]; }
3. 元素删除
关于ArrayList元素的删除,提供了4个方法:
public E remove(int index)public boolean remove(Object o)public void clear() public boolean removeAll(Collection<?> c)public boolean retainAll(Collection<?> c)
remove(int index)方法,删除指定位置的元素
public E remove(int index) { rangeCheck(index);// 校验index向上是否越界,越界则抛出异常 modCount++;// 扩容的时候++,删除也++,记录操作次数 E oldValue = elementData(index);// 获取指定位置的元素 int numMoved = size - index - 1; // elementData index后面的元素向前移动一位 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); // --size,elementData尾部元素置为null,GC可以回收 elementData[--size] = null; return oldValue;// 返回已删除的元素 }
remove(Object o)方法,删除数组中第一个为o的元素
public boolean remove(Object o) { // 遍历数组,删除第一个为null的元素并返回 if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { http://www.cnblogs.com/yy1024/p/7068199.html