ArrayList基于数组实现,是一个动态的数组队列,空间(增删)效率不高,时间(查询)效率很高。可是它和Java中的数组又不同,它的容量能够自动增加。当集合中的元素超出这个容量,便会进行扩容操做。扩容操做也是ArrayList 的一个性能消耗比较大的地方,因此若咱们能够提早预知数据的规模,应该指定集合的大小,去构建ArrayList实例,以减小扩容次数,提升效率。或者在须要扩容的时候,手动调用 ensureCapacity(int minCapacity) 方法扩容。 html
ArrayList继承了AbstractList,实现了RandomAccess、Cloneable和Serializable接口。java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
AbstractList又继承了AbstractCollection实现了List接口,它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。api
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractList() { }
实现了RandomAccess接口,提供了随机访问功能,实际上就是经过下标序号进行快速访问。
实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
实现了Serializable接口,支持序列化,也就意味了ArrayList可以经过序列化传输。数组
java.lang.Object ↳ java.util.AbstractCollection<E> ↳ java.util.AbstractList<E> ↳ java.util.ArrayList<E> public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
API详解安全
一、elementData 是"Object[]类型的数组",它保存了添加到ArrayList中的元素。实际上,elementData是个动态数组,咱们能经过构造函数 ArrayList(int initialCapacity)来执行它的初始容量为initialCapacity;若是经过不含参数的构造函数ArrayList()来建立ArrayList,则elementData的容量默认是10。elementData数组的大小会根据ArrayList容量的增加而动态的增加,具体的增加方式,请参考源码分析中的ensureCapacity()函数。
二、size 则是动态数组的实际大小。多线程
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /************************ 属性 **********************************/ //默认初始容量 = 10 private static final int DEFAULT_CAPACITY = 10; //用于空实例的共享空数组实例。 private static final Object[] EMPTY_ELEMENTDATA = {}; //存储ArrayList的元素的数组缓冲区。 //ArrayList的容量是该数组缓冲区的长度。 //任何空的ArrayList与elementData == EMPTY_ELEMENTDATA将被扩展为添加第一个元素时的DEFAULT_CAPACITY。 //注:被transient关键字修饰的变量再也不能被序列化,一个静态变量不论是否被transient修饰,均不能被序列化。 private transient Object[] elementData; //ArrayList的大小(它包含的元素数量)。 private int size; /************************ 构造函数 ********************************/ /** * 构造具备指定初始容量的空列表 * @param initialCapacity 列表的初始容量 * @throws IllegalArgumentException 若是指定的初始容量是负数 */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } /** * 构造一个初始容量为10的空列表 */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 按照集合的迭代器返回的顺序构造包含指定集合的元素的列表 * @param c 其元素将被放置到此列表中的集合 * @throws 若是指定的集合为null,则为NullPointerException */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; //判断是否返回Object[].class,若没有返回,则使用Arrays.copyOf 进行转换 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } /***************************** 方法 ****************************************/ /** *将此 ArrayList 实例的容量修改成列表的当前大小。 *应用程序可使用此操做最小化 ArrayList 实例的存储。 */ public void trimToSize() { modCount++;//在java.util.AbstractList<E>中定义,用于计算对数组的操做次数 if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } } /** * 若有必要,增长此 ArrayList 实例的容量,以确保由最小容量参数指定。 * @param minCapacity 所需的最小容量 */ public void ensureCapacity(int minCapacity) { int minExpand = (elementData != EMPTY_ELEMENTDATA) ? 0 : 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++; if (minCapacity - elementData.length > 0) grow(minCapacity); } /** *一些虚拟机保留数组中的一些标题字。 *尝试分配较大的数组可能会致使OutOfMemoryError:请求的数组大小超过VM限制 * 注:怕超过VM限制,因此只用 Integer.MAX_VALUE - 8 设置MAX_ARRAY_SIZE的值! */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 增长容量以确保它至少能够容纳由最小容量参数指定的元素数。 * @param minCapacity 所需的最小容量 */ private void grow(int minCapacity) { // overflow-conscious code 溢出-察觉代码 int oldCapacity = elementData.length; //旧的容量大小 int newCapacity = oldCapacity + (oldCapacity >> 1); //oldCapacity >> 1 : >> 右移 至关于 oldCapacity/2 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity);//看下面的hugeCapacity()方法,数组的最大容量不会超过MAX_ARRAY_SIZE // minCapacity一般接近于大小,因此这是一个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; } /** * 返回此列表中的元素数。获取集合的大小 * @return 此列表中的元素数 */ public int size() { return size; } /** * 判断是否为空,若是集合为没有包含任何元素,返回 true */ public boolean isEmpty() { return size == 0; } /** *若是此列表包含指定的元素,则返回true。 更正式地, *当且仅当这个列表包含至少一个元素e使得(o == null?e == *null:o.equals(e))时, *返回true。 * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** *返回此列表中指定元素的第一次出现的索引,若是此列表不包含元素, *则返回-1。 更正式地,返回最低索引i,使得(o == null?get(i)== null:o.equals(get(i))), *或-1,若是没有这样的索引。 * *返回:此列表中指定元素的第一次出现的索引,若是此列表不包含元素,则为-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; } /** * 返回此列表中指定元素的最后一次出现的索引,若是此列表不包含元素, *则返回-1。 更正式地,返回最高索引i,使得(o == null?get(i)== null:o.equals(get(i))), *或-1若是没有这样的索引。 * *返回:此列表中指定元素的最后一次出现的索引,若是此列表不包含元素,则为-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; } /** * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves are not copied.) * 返回此<tt> ArrayList </ tt>实例的浅拷贝。 (元素自己不被复制。) * @return a clone of this <tt>ArrayList</tt> instance */ public Object clone() { //实现了Cloneable接口,覆盖了函数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(); } } /** * 以正确的顺序返回包含此列表中全部元素的数组(从第一个元素到最后一个元素)。 * * <p>This method acts as bridge between array-based and collection-based * APIs. * 此方法充当基于阵列和基于集合的API之间的桥梁 * @return an array containing all of the elements in this list in * proper sequence * 一个包含正确顺序的列表中全部元素的数组 */ public Object[] toArray() { return Arrays.copyOf(elementData, size);//使用Arrays工具类 } /** * Returns the element at the specified position in this list. * 返回此列表中指定位置的元素。 * * @param index index of the element to return * 要返回的元素的索引索引 * @return the element at the specified position in this list * 该列表中指定位置的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { rangeCheck(index); return elementData(index); } /** * Replaces the element at the specified position in this list with * the specified element. * 用指定的元素替换此列表中指定位置处的元素。 * * @param index index of the element to replace * 要替换的元素的索引索引 * @param element element to be stored at the specified position * 元素要素存储在指定位置 * @return the element previously at the specified position * 元素先前在指定位置 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * Appends the specified element to the end of this list. * 将指定的元素追加到此列表的末尾。 * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! 增长modCount!用于判断 elementData[size++] = e; return true; } /** * Inserts the specified element at the specified position in this * list. Shifts the element currently at that position (if any) and * any subsequent elements to the right (adds one to their indices). * 在此列表中指定的位置插入指定的元素。 将当前在该位置的元素(若是有) * 和任何后续元素向右移(将一个添加到它们的索引)。 * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ 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++; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * 删除此列表中指定位置的元素。 将任何后续元素向左移(从它们的索引中减去一个)。 * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ 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, //public static native void arraycopy(Object src, int srcPos, // Object dest, int destPos,int length); //调用了本地的方法 : 将指定源数组的数组从指定位置开始复制到目标数组的指定位置。 elementData[--size] = null; // clear to let GC do its work 设置为 null ,让gc去回收 return oldValue; } /** * Removes the first occurrence of the specified element from this list, * if it is present. If the list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * 从列表中删除指定元素的第一次出现(若是存在)。 *若是列表不包含元素,则不会更改。 更正式地,删除具备最低索引i的元素,使得(若是这样的元素存在) *(o == null?get(i)== *null:o.equals(get(i)))。 *若是此列表包含指定的元素(或等效地,若是此列表做为调用的结果更改),则返回true。 * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element 若是包含返回 true */ 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 remove method that skips bounds checking and does not * return the value removed. * 私有删除方法,跳过边界检查,不返回值删除。 */ 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 } /** * Removes all of the elements from this list. The list will * be empty after this call returns. *今后列表中删除全部元素。 此调用返回后,列表将为空 */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 将指定集合中的全部元素以指定集合的Iterator返回的顺序追加到此列表的末尾。 *若是在操做正在进行时修改指定的集合,则此操做的行为是未定义的。 *(这意味着若是指定的集合是此列表,则此调用的行为是未定义的,而且此列表不是空的。) * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ 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; } /* *将指定集合中的全部元素插入到此列表中,从指定位置开始。 * */ 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; } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). *今后列表中删除其索引在fromIndex(包含)和toIndex(排除)之间的全部元素。 *将任何后续元素向左移(减小其索引)。 */ 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)); } /** * A version of rangeCheck used by add and addAll. * 由add和addAll使用的rangeCheck的版本。 * 私有方法 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Removes from this list all of its elements that are contained in the * specified collection. * 今后列表中删除包含在指定集合中的全部元素。 * @param c collection containing elements to be removed from this list * @return {@code true} if this list changed as a result of the call * 若是此列表因为调用而更改 则返回true */ public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes from this list all * of its elements that are not contained in the specified collection. *仅保留此列表中包含在指定集合中的元素。 换句话说, *今后列表中删除未包含在指定集合中的全部元素。 * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * 若是此列表因为调用而更改 则返回true */ 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. //保留与AbstractCollection的行为兼容性,即便c.contains()抛出。 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实例的状态保存到流(即,序列化它)。 */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff //写出元素数量和任何隐藏的东西 int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, * deserialize it). *从流重构 ArrayList 实例(即,反序列化它)。 */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff //读出元素数量和任何隐藏的东西 s.defaultReadObject(); // Read in capacity 读入容量 s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } } /** *对列表中的元素返回一个列表迭代器(以正确的顺序), *从列表中指定的位置开始。 指定的索引指示由初始调用返回到next的第一个元素。 *对上一个的初始调用将返回具备指定索引减1的元素。 * *返回的列表迭代器是fail-fast的。 * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * Returns a list iterator over the elements in this list (in proper * sequence). *返回此列表中的元素(按正确顺序)的列表迭代器。 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. *返回的列表迭代器是fail-fast的。 * @see #listIterator(int) */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * Returns an iterator over the elements in this list in proper sequence. *以正确的顺序返回此列表中的元素的迭代器。 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. *返回的列表迭代器是fail-fast的。 * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr * AbstractList.Itr的优化版本 */ 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(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * An optimized version of AbstractList.ListItr * AbstractList.ListItr的优化版本 */ 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(); } } } //subList 以及后面的代码不在作分析,实际状况中不多用到,须要的时候,请自行看源码分析 }
一、ArrayList 本质实现方法是用数组!是非同步的,即多线程非安全
二、初始化容量 = 10 ,最大容量不会超过 MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
三、indexOf和lastIndexOf 查找元素,若元素不存在,则返回-1
四、当ArrayList容量不足以容纳所有元素时,ArrayList会从新设置容量:新的容量=(原始容量x3)/2
五、ArrayList的克隆函数,便是将所有元素克隆到一个数组中
六、ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写入“每个元素”;当读出输入流时,先读取“容量”,再依次读取“每个元素”
七、从代码中能够看出,当容量不够时,每次增长元素,都要将原来的元素拷贝到一个新的数组中,很是之耗时,也所以建议在事先能肯定元素数量的状况下,才使用ArrayList,不然建议使用LinkedList
八、ArrayList基于数组实现,能够经过下标索引直接查找到指定位置的元素,所以查找效率高,但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低
九、在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种状况处理,ArrayList中容许元素为nullapp
import java.util.*; import java.util.concurrent.*; /* * @desc ArrayList遍历方式和效率的测试程序。 * * @author skywang */ public class ArrayListRandomAccessTest { public static void main(String[] args) { List list = new ArrayList(); for (int i=0; i<100000; i++) list.add(i); //isRandomAccessSupported(list); iteratorThroughRandomAccess(list) ; iteratorThroughIterator(list) ; iteratorThroughFor2(list) ; } private static void isRandomAccessSupported(List list) { if (list instanceof RandomAccess) { System.out.println("RandomAccess implemented!"); } else { System.out.println("RandomAccess not implemented!"); } } //经过索引值去遍历 效率最快 public static void iteratorThroughRandomAccess(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for (int i=0; i<list.size(); i++) { list.get(i); } endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughRandomAccess:" + interval+" ms"); //输出 3 ms } //迭代器遍历 效率最慢 public static void iteratorThroughIterator(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for(Iterator iter = list.iterator(); iter.hasNext(); ) { iter.next(); } endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughIterator:" + interval+" ms"); // 输出 8 ms } //for循环遍历 效率低于索引遍历 高于迭代器 public static void iteratorThroughFor2(List list) { long startTime; long endTime; startTime = System.currentTimeMillis(); for(Object obj:list) ; endTime = System.currentTimeMillis(); long interval = endTime - startTime; System.out.println("iteratorThroughFor2:" + interval+" ms"); //输出 5 ms } }
遍历ArrayList时,经过索引序号访问效率最高,而使用迭代器的效率最低。dom
ArrayList提供了2个toArray()函数函数
Object[] toArray() <T> T[] toArray(T[] contents)
调用 toArray() 函数会抛出“java.lang.ClassCastException”异常,可是调用 toArray(T[] contents) 能正常返回 T[]。
toArray() 会抛出异常是由于 toArray() 返回的是 Object[] 数组,将 Object[] 转换为其它类型(如如,将Object[]转换为的Integer[])则会抛出“java.lang.ClassCastException”异常,由于Java不支持向下转型。具体的能够参考前面ArrayList.java的源码介绍部分的toArray()。
解决该问题的办法是调用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。工具
// toArray(T[] contents)调用方式一 public static Integer[] vectorToArray1(ArrayList<Integer> v) { Integer[] newText = new Integer[v.size()]; v.toArray(newText); return newText; } // toArray(T[] contents)调用方式二。最经常使用! public static Integer[] vectorToArray2(ArrayList<Integer> v) { Integer[] newText = (Integer[])v.toArray(new Integer[0]); return newText; } // toArray(T[] contents)调用方式三 public static Integer[] vectorToArray3(ArrayList<Integer> v) { Integer[] newText = new Integer[v.size()]; Integer[] newStrings = (Integer[])v.toArray(newText); return newStrings; }
若是内容对你有帮助但愿点赞收藏谢谢!!!