ArrayList基本使用
public class ArrayListTest {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("5");
System.out.println(list.get(0));
}
}
ArrayList繼承層次
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
基本字段
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
//默認(rèn)的初始化容量
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
//空數(shù)組,會在構(gòu)造函數(shù)中給予0參數(shù)的情況下,賦值給elementData
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.
*/
//在一個個元素加入進(jìn)來的時候,會自動擴(kuò)展成為DEFAULTCAPACITY
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.
*/
//真正的數(shù)組的引用
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
//添加的元素數(shù)量
private int size;
/**
* 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
*/
//是因為有header words?才導(dǎo)致要Integer的最大值減8
//其實這個變量只在后面使用一次,比較了之后,然后還是按照MAX_VALUE來擴(kuò)容了...為啥
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
構(gòu)造函數(shù)
/**
* 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
*/
//帶有初始化容量的構(gòu)造函數(shù)
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//初始化一個initialCapacity大小的Object數(shù)組
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//若初始化為0,則使用默認(rèn)的空數(shù)組賦值
this.elementData = EMPTY_ELEMENTDATA;
} else {
//若為負(fù)數(shù),拋出非法參數(shù)異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
//最基本的構(gòu)造函數(shù)
public ArrayList() {
//注意這里被賦值為DEFAULTCAPACITY_EMPTY_ELEMENTDATA
//而不是EMPTY_ELEMENTDATA,表示的意思就是當(dāng)add的時候
//會默認(rèn)擴(kuò)容為DEFAULT_CAPACITY
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 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;
}
}
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) {
//添加元素的時候,調(diào)用內(nèi)部確保容量的方法
//為什么是內(nèi)部呢?因為還有一個共有的ensureCapacity方法
ensureCapacityInternal(size + 1); // Increments modCount!!
//因為本身是一個數(shù)組,所以在下一個數(shù)組索引位置添加上元素
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//如果elementDate等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA
//表示第一次擴(kuò)容時,起碼要擴(kuò)容至DEFAULT_CAPACITY
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//取DEFAULT_CAPACITY=10和minCapacity(可以在初始化函數(shù)中初始化)的最大值
//也就是說若調(diào)用默認(rèn)構(gòu)造函數(shù),第一次會起碼擴(kuò)展為10的大小
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//確保顯示的容量
ensureExplicitCapacity(minCapacity);
}
其實ensureCapacityInternal一個任務(wù)是算出不論是第一次添加導(dǎo)致的擴(kuò)容還是后面添加導(dǎo)致的擴(kuò)容的最小的容量值。然后將這個最小擴(kuò)容值傳遞給ensureExplicitCapacity,由ensureExplicitCapacity實現(xiàn)擴(kuò)容。
private void ensureExplicitCapacity(int minCapacity) {
//用于迭代器的fail fast機(jī)制
modCount++;
// overflow-conscious code
//如果最小容量大于數(shù)組的長度,那么擴(kuò)容。
//否則,則不擴(kuò)容。
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* 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;
//新的容量為舊的容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果擴(kuò)了1.5倍之后,還是小,那么以最小的容量進(jìn)行擴(kuò)容
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擴(kuò)展為newCapacity大小,使用復(fù)制數(shù)組的方式
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
//如果minCapacity小于0(而minCapacity是由某數(shù)+1得到)
//其實也剛開始想錯了,minCapacity也有可能是addAll()調(diào)用導(dǎo)致的
//反正minCapacity是一個需要保證的最小的容量值,不需要去理解
//其他函數(shù)是如何調(diào)用的
//所以minCapacity是由于Integer溢出的
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
//這里表示將最大容量擴(kuò)展為Integer.MAX_VALUE,那么MAX_ARRAY_SIZE還有什么意義呢?
//這里minCapacity沒有溢出說明是小于MAX_ARRAY_SIZE,但是分為兩種情況,如果小于MAX_ARRAY_SIZE
//那么就直接擴(kuò)容為MAX_ARRAY_SIZE
//否則比如說是MAX_VALUE-2,那么最多擴(kuò)容為MAX_VALUE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
get操作
/**
* 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);
//返回數(shù)組的值
return elementData(index);
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
//如果下標(biāo)大于元素的數(shù)量,那么拋出異常
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
remove操作
/**
* 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);
//add和remove都需要讓modCount加一
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//最大位的引用置為null,讓GC回收
elementData[--size] = null; // clear to let GC do its work
//返回刪除的值
return oldValue;
}
參考
自己動手系列——實現(xiàn)一個簡單的ArrayList
Arrays.copyof(···)與System.arraycopy(···)區(qū)別
Java提高篇(三四)—–fail-fast機(jī)制
why-the-maximum-array-size-of-arraylist-is-integer-max-value-8---其實并不是按照Integer.MAX_VALUE - 8來進(jìn)行的
Java中ArrayList最大容量為什么是Integer.MAX_VALUE-8?---感覺知乎上面理解的對一些
Why I can't create an array with large size?----還有這個Java里面數(shù)組最大可以開多大