java arraylist 构造_Java ArrayList构造分析

本文详细介绍了ArrayList的内部实现,包括它如何使用Object数组elementData存储元素以及size属性记录元素数量。当添加元素时,通过ensureCapacity方法检查并调整数组容量,以确保能够容纳新增元素。在删除元素时,会移动后续元素并更新size。ArrayList的扩容策略是将原容量的1.5倍作为新的容量,确保高效操作。
摘要由CSDN通过智能技术生成

1 /**2 * The array buffer into which the elements of the ArrayList are stored.

3 * The capacity of the ArrayList is the length of this array buffer.

4*/

5 private transientObject[] elementData;6

7 /**8 * The size of the ArrayList (the number of elements it contains).

9 *

10 *@serial11*/

12 private int size;

从这里看出, ArrayList是用Array来实现的,包括elementData数组和其大小两个属性。

1 public booleanadd(E e) {2 ensureCapacity(size + 1); //Increments modCount!!

3 elementData[size++] =e;4 return true;5 }

/*** Increases the capacity of this ArrayList instance, if

* necessary, to ensure that it can hold at least the number of elements

* specified by the minimum capacity argument.

*

*@paramminCapacity the desired minimum capacity*/

public void ensureCapacity(intminCapacity) {

modCount++;int oldCapacity =elementData.length;if (minCapacity >oldCapacity) {

Object oldData[]=elementData;int newCapacity = (oldCapacity * 3)/2 + 1;if (newCapacity

newCapacity=minCapacity;//minCapacity is usually close to size, so this is a win:

elementData =Arrays.copyOf(elementData, newCapacity);

}

}

ensureCapacity ensure that the inner array size satisfy the add(Object o) operation. If minCapacity is bigger than the original array size, it increase the array size and do the checking again. ensureCapacity() will increase the array size by at least 1. After the array size is OK, copy original array into new array with bigger size. After ensureCapacity() is returned, set elementData[size] to be the newly added element. Since the array size is increased by at least one. call elementData[size] will not throw exception.

public E remove(intindex) {

RangeCheck(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; //Let gc do its work

returnoldValue;

}

1 /**

2 * Checks if the given index is in range.3 */

4 private void RangeCheck(intindex) {5 if (index >=size)6 throw newIndexOutOfBoundsException(7 "Index: "+index+", Size: "+size);8 }

Remove(int index):

Check if index is out of range. Store the removed object. Move all elements after index one position forward. Mark element of size-1 to be null.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值