ArrayList解析

来源:互联网 发布:时时彩做计划软件 编辑:程序博客网 时间:2024/05/17 17:39
1.说明:
ArrayList内部实现是以数组实现,其最重要的一点就是能够自动扩容,也就是我们常常说的"动态数组",当超出其长度限制的时候会扩展为原来的1.5倍,如果扩展1.5倍还不满足需求,直接扩展为需求值,其默认容量为10。
2.源码解析:
(1)add函数
public boolean add(E e) {

ensureCapacityInternal(size + 1);
elementData[size++] = e;

return true;

}
(2)put函数
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)get函数
public E get(int index) {

if (index >= size)

throw new IndexOutOfBoundsException(outOfBoundsMsg(index));


return (E) elementData[index];

}
(4)remove函数
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;

}
(5)ensureCapacityInternal自动扩容机制
private void ensureCapacityInternal(int minCapacity) {

if (elementData == 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;

// 扩展为原来的1.5倍
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);

}
原创粉丝点击