java集合: ArrayList源码浅析

时间:2023-03-09 15:07:11
java集合: ArrayList源码浅析

ArrayList 是一个动态数组,线程不安全 ,允许元素为null。

ArrayList的数据结构是数组,查询比较方便。

ArrayList类的接口

public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{

RandomAccess:RandmoAccess是一个标记接口,用于被List相关类实现。他主要的作用表明这个相关类支持快速随机访问。在ArrayList中,我们即可以通过元素的序号快速获取元素对象——这就是快速随机访问。除了List的“快速随机访问”,还可以“通过Iterator迭代器访问”。
Cloneable:实现该接口的类可以对该类的实例进行克隆(按字段进行复制)。
Serializable:ArrayList支持序列化,能通过序列化去传输。

构造方法

ArrayList(),初始化的时候,先分配一个空数组。添加一个元素时,容量就会扩展到DEFAULT_CAPACITY,也就是10。

   /**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_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.
*
* 初始化的时候,分配一个空数组。添加一个元素时,容量就会扩展到DEFAULT_CAPACITY,也就是10。
* 关键字transient表示属性不会被序列化。
*/
transient Object[] elementData; // non-private to simplify nested class access /**
* Default initial capacity.
* 默认容量为10
*/
private static final int DEFAULT_CAPACITY = 10;

往ArrayList中添加数据的方法add() 如下:

  /**
* 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;
}

扩容时,ensureCapacityInternal()方法内部调用的是grow()方法。

数组扩容。如果插入数据时容量不够,就将容量扩大为1.5倍。
扩容的过程就是数组拷贝 Arrays.copyOf的过程,每一次扩容就会开辟一块新的内存空间和数据的复制移动
 grow()方法 如下所示:

  /**
* 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;
// 左移一位表示原来的0.5倍,以下是将容量扩大为1.5倍
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);
}

get(int 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) {
rangeCheck(index); return elementData(index);
} @SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}

参考博客 :

https://www.jianshu.com/p/02f8696bf4cf