ArrayList的具体实现
ArrayList是List接口的具体实现,是在实际生产环境中用的非常多的一种工具类
数据结构
- 顾名思义,从ArrayList的名字中我们就可以看出,ArrayList是基于数组的一种实现.
private transient Object[] elementData; //对象存储
private int size; //实际含有对象的大小 size <= elementData.length
主要代码实现
构造函数
// 构造函数比较简单, 初始化对象数组就可以了
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
add
//将对象添加到数组的末尾即可
public boolean add(E e) {
ensureCapacityInternal(size + 1); //对List进行扩容
elementData[size++] = e;
return true;
}
//在index位置添加新的数据, >=index的则全部后移一位
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // 扩容
System.arraycopy(elementData, index, elementData, index + 1,
size - index); // 后移
elementData[index] = element;
size++;
}
//扩容实现
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // 计算扩容后的数组大小 JDK > 1.7的算法, 与1.7以前的算法不同
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);
}
set
//替换index的原有数据
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
get
//直接取值, 数组结构的最大优势
E elementData(int index) {
return (E) elementData[index];
}
remove
//根据index remove
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = 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;
}
//根据Object remove
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;
}
其余函数基本与这几个类似
迭代器, TODO:暂时还没看太明白,改天继续分析
时间: 2024-11-03 21:46:01