Android 开发也要懂得数据结构 - ArrayList源码
Posted 进击的包籽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 开发也要懂得数据结构 - ArrayList源码相关的知识,希望对你有一定的参考价值。
文章目录
- 1.ArrayList特点
- 2.ArrayList的继承关系
- 3.ArrayList的常用方法
- 3.1 构造方法
- 3.2 尾部插入 add(E e)
- 3.3 中间插入 add(int index, E element)
- 3.4 扩容 grow(int minCapacity)
- 3.5 获取元素 get(int index)
- 3.6 删除索引位置 remove(int index)
- 3.7 删除指定元素 remove(Object o)
- 3.8 修改元素 set(int index, E element)
- 3.9 内容长度 size()
- 3.10 判断是否为空 isEmpty()
- 3.11 清空列表 clear()
- 3.12 转化为数组 toArray()
- 3.13 找到元素的下标 indexOf(Object o)
- 3.14 是否包含元素 contains(Object o)
- 3.15 index,contains注意事项
- 3.16 批量添加数据 addAll(Collection<? extends E> c)
- 3.17 在中间批量插入数据 addAll(int index, Collection<? extends E> c)
- android 开发,ArrayList 是最常用的数据结构之一,所以我们需要了解一下ArrayList的知识。
- LinkList源码分析点击这里
- 本文章使用的是 JDK1.8 ,不同版本源码有差异。
1.ArrayList特点
- ArrayList是顺序表,支持随机访问,所以查找速度快,set、get操作速度快。
- ArrayList尾部插入删除的速度快,但中间插入、删除的效率低,因为要移动后面的元素。
- Android开发中,如果大部分是查找操作,就适合使用ArrayList,插入删除多的适合使用LinkList。
- ArrayList是非线程安全的,Vector线程安全。
- 查看源码我们才能了解扩容机制等知识。
2.ArrayList的继承关系
- 下图是ArrayList的继承关系,可以查看源码找到下面的关系。
3.ArrayList的常用方法
3.1 构造方法
- 填写容量大小的构造方法,就指定了初始的容量,如果你知道自己需要多大的数据时,最好初始化就填入这个值,因为不写的话,后面每次扩容,还是需要消耗一些性能与资源的。写了大小就一步到位,省去扩容的操作。
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
- 在不填写传入参数时,ArrayList就是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA ,默认数组大小为0,但是注释给的是默认大小10,add时再说。
/**
* 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 = ;
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList()
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
- 构造方法也能传入 Collection 类,实现转化。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @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();
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;
3.2 尾部插入 add(E e)
- ArrayList创建的时候,默认数组大小是0,但add操作时,数组会扩容到10。
- 通过源码可以看到,add时,如果数组是 DEFAULTCAPACITY_EMPTY_ELEMENTDATA ,就会进行第一次扩容,大小为 DEFAULT_CAPACITY ,也就是10。
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 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!!
elementData[size++] = e;
return true;
private void ensureCapacityInternal(int minCapacity)
if (elementData == DEFAULTCAPACITY_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);
3.3 中间插入 add(int index, E element)
- 如果插入的 index 越界了,就会报异常。
- 插入后,如果索引位置后侧有数据,那这些数据都要移动 arraycopy。
/**
* 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)
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
3.4 扩容 grow(int minCapacity)
- ArrayList大小不够用的时候,就会扩容,大小为原来的1.5倍(老数组大小 + 老数组右移一位,就是除以2),位运算速度更快。
- 如果扩容1.5倍依然不够用,就把需要最低的大小设置为扩容大小。
- 如果大小超过了 MAX_ARRAY_SIZE (这是非常大的数,可能会超过虚拟机内存大小),就判断是否大于 Integer.MAX_VALUE ,是就用 Integer.MAX_VALUE ,否则用 MAX_ARRAY_SIZE 作为数组大小。
- 然后再将老的数据 copy 到新的数组。
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity)
// overflow-conscious code
int oldCapacity = elementData.length;
//新的大小为老数组大小 + 老数组右移一位
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果扩容1.5倍依然不够用,就把需要最低的大小设置为扩容大小。
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();
//如果minCapacity大于Integer.MAX_VALUE,就用Integer.MAX_VALUE,否则用MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
3.5 获取元素 get(int index)
- 直接返回数组下标对应的元素,如果index 大于长度,报异常。
/**
* 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)
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
3.6 删除索引位置 remove(int index)
- 删除指定位置的数据,删除的位置如果是中间,索引位置后面的元素就要往前移动。
/**
* 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)
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) 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;
3.7 删除指定元素 remove(Object o)
- 这个删除操作就需要遍历所有数据,找到指定的数据进行删除,相比 remove(int index) 效率低。
- ArrayList是可以存放 null 的。
/**
* 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
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
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;
3.8 修改元素 set(int index, E element)
- 修改索引位置的元素。
/**
* 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)
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
3.9 内容长度 size()
- 注意这是返回的是元素的长度,而不是数组的长度。
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size()
return size;
3.10 判断是否为空 isEmpty()
- 用的就是 size 是否为 0 来判断,这个方法注意,ArrayList 为空指针时,调这个方法就会报空指针异常。
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
public boolean isEmpty()
return size == 0;
3.11 清空列表 clear()
- 循环将所有索引位置的数据设为 null ,但容量还是在的。
/**
* 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;
3.12 转化为数组 toArray()
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray()
return Arrays.copyOf(elementData, size);
3.13 找到元素的下标 indexOf(Object o)
- 返回指定元素第一次出现的索引。
- 如果此列表不包含元素,则返回-1。
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
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;
3.14 是否包含元素 contains(Object o)
- 使用的是 ** index** 方法,至少有一个元素就返回 ** true** 。
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @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;
3.15 index,contains注意事项
- index,lastIndexOf ,contains 方法需要重写对象的 equals 方法。
3.16 批量添加数据 addAll(Collection<? extends E> c)
- 在队列尾部批量添加数据
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @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;
3.17 在中间批量插入数据 addAll(int index, Collection<? extends E> c)
- 在中间批量插入数据,索引后面的元素全部后移。
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @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 IndexOutOfBoundsException @inheritDoc
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c)
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
以上是关于Android 开发也要懂得数据结构 - ArrayList源码的主要内容,如果未能解决你的问题,请参考以下文章
Android 开发也要懂得数据结构 - ArrayList源码
Android 开发也要懂得数据结构 - LinkList源码