ArrayList 源碼分析
// 默認(rèn)情況下,數(shù)組的初始化大小
private static final int DEFAULT_CAPACITY = 10;
// 空數(shù)組
private static final Object[] EMPTY_ELEMENTDATA = {};
// 空數(shù)組
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 數(shù)據(jù)
transient Object[] elementData; // non-private to simplify nested class access
// 數(shù)據(jù)大小
private int size;
// 給數(shù)組指定初始化大小
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);
}
}
// 不指定大小的話默認(rèn)給數(shù)組指定初始化大小為10
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
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);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 默認(rèn)情況下擴(kuò)充為原來的一半
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:
// 創(chuàng)建一個(gè)新數(shù)組并把原來數(shù)組里的內(nèi)容拷貝到新數(shù)組中
elementData = Arrays.copyOf(elementData, newCapacity);
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
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;
}
public int size() {
return size;
}
// 通過 native 層去拷貝代碼
// src :原來的數(shù)組
// srcPos:原來數(shù)組的開始位置
// dest:新的數(shù)組
// destPos:新數(shù)組的開始位置
// length:拷貝多少個(gè)
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
通過上面的代碼來分析,ArrayList 其內(nèi)部的實(shí)現(xiàn)方式其實(shí)就是數(shù)組,如果沒指定數(shù)組的大小,那么在第一次添加數(shù)據(jù)的時(shí)候,數(shù)組的初始大小是 10 ,每次當(dāng)不夠用的時(shí)候默認(rèn)會(huì)擴(kuò)充原來數(shù)組的 1/2 ,每次擴(kuò)充數(shù)組大小都會(huì)涉及到創(chuàng)建新數(shù)組和數(shù)據(jù)的拷貝復(fù)制。而數(shù)組的拷貝和邏動(dòng)都是由我們的 native 層代碼實(shí)現(xiàn),接下來我們簡(jiǎn)單實(shí)現(xiàn)native層ArrayList邏輯。
實(shí)現(xiàn) Native 層的 ArrayList
#include<malloc.h>
#include<memory.h>
#include <iostream>
using namespace std;
template<class E>
class ArrayList
{
public:
//數(shù)組頭指針
E* elementData = NULL;
//數(shù)組長度
int index = 0;
//數(shù)組容量大小
int size = 0;
public:
ArrayList();
ArrayList(int size);
ArrayList(const ArrayList& list);
~ArrayList();
public:
bool add(E e);
int len();
int capacity();
E get(int index);
E remove(int index);
private:
void ensureCapacityInternal(int minCapacity);
void grow(int minCapacity);
};
template<class E>
ArrayList<E>::ArrayList()
{
cout << "無參構(gòu)造" << endl;
}
template<class E>
ArrayList<E>::ArrayList(int size)
{
cout << "帶參構(gòu)造" << endl;
if (size == 0) {
return;
}
this->size = size;
this->elementData = (E*)malloc(sizeof(E) * size);
}
template<class E>
ArrayList<E>::ArrayList(const ArrayList& list)
{
cout << "拷貝構(gòu)造" << endl;
this->size = list.size;
this->index = list.index;
this->elementData = (E*)malloc(sizeof(E) * size);
memcpy(this->elementData, list.elementData, sizeof(E) * size);
}
template<class E>
ArrayList<E>::~ArrayList()
{
cout << "析構(gòu)函數(shù)" << endl;
if (this->elementData) {
free(this->elementData);
this->elementData = NULL;
}
}
template<class E>
bool ArrayList<E>::add(E e)
{
ensureCapacityInternal(index + 1);
this->elementData[index++] = e;
return true;
}
template<class E>
int ArrayList<E>::len()
{
return this->index;
}
template<class E>
int ArrayList<E>::capacity()
{
return this->size;
}
template<class E>
E ArrayList<E>::get(int index)
{
return this->elementData[index];
}
template<class E>
E ArrayList<E>::remove(int index)
{
E oldValue = this->elementData[index];
int needMoved = this->index - index - 1;
int i = 0;
for (i; i < needMoved; i++)
{
this->elementData[index + i] = this->elementData[index + i + 1];
}
this->index -= 1;
return oldValue;
}
template<class E>
void ArrayList<E>::ensureCapacityInternal(int minCapacity)
{
if (this->elementData == NULL)
{
minCapacity = 10;
}
if (minCapacity - size > 0)
{
grow(minCapacity);
}
}
template<class E>
void ArrayList<E>::grow(int minCapacity)
{
int newCapacity = size + (size >> 1);
if (newCapacity - minCapacity < 0)
{
newCapacity = minCapacity;
}
E* new_arr = (E*)malloc(sizeof(E) * newCapacity);
if (this->elementData)
{
memcpy(new_arr, this->elementData, sizeof(E) * index);
free(this->elementData);
}
this->elementData = new_arr;
size = newCapacity;
}
int main() {
//ArrayList<int> list = { 4 };
//ArrayList<int> list(4);
//list.add(1);
//list.add(2);
//list.add(3);
//int i = 0;
//for (i; i < list.index; i++)
//{
// cout << "i:" << list.get(i) << endl;
//}
ArrayList<int>* list = new ArrayList<int>(5);
list->add(1);
list->add(2);
list->add(3);
cout << "remove 前 len:" << list->len() << " capacaity:" << list->capacity() << endl;
int i = 0;
for (i; i < list->index; i++)
{
cout << "i:" << list->get(i) << endl;
}
list->remove(1);
cout << "remove 后 len:" << list->len() << " capacaity:" << list->capacity() << endl;
i = 0;
for (i; i < list->index; i++)
{
cout << "i:" << list->get(i) << endl;
}
getchar();
return 0;
}
運(yùn)行結(jié)果
帶參構(gòu)造
remove 前 len:3 capacaity:5
i:1
i:2
i:3
remove 后 len:2 capacaity:5
i:1
i:3