- // 添加指定元素到list末尾
- 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) {
- // 比较默认的容量10和传入的容量,返回大点的数
- 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
- // 记录当前list的容量
- 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);
- }
也就是说,当增加数据的时候,如果 ArrayList 的大小已经不满足需求时,那么数组大小就会变为原来的 1.5 倍,之后就是把老的数据拷贝新的数组里面。例如我创建的 list 的容量时 10,当我们已经添加了 10 个元素的之后,再添加就会进行自动扩容到 15。
- public E get(int index) {
- rangeCheck(index);
- return elementData(index);
- }
- public E set(int index, E element) {
- rangeCheck(index);
- E oldValue = elementData(index);
- elementData[index] = element;
- return oldValue;
- }
get() 和 set() 就比较简单了,进行范围检查后就可以进行对应的操作了。由于 ArrayList 是动态数组,所以我们完全可以根据下标来获取 ArrayList 中的元素,而且速度还比较快,故 ArrayList 长于随机访问。
remove() 首先进行范围检查,然后计算移动的开始位置,如果大于 0 的话就进行移动并返回旧值
- 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;
- }
参考文章:
来源: http://www.cnblogs.com/lebo0425/p/6504658.html