底层的数组对象

 /**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
//ArrayList底层的数组对象
private transient Object[] elementData;

get(int index) 方法

     public E get(int index) {
//先对角标进行校验,看看是否越界
rangeCheck(index); return elementData(index);
} //throws an ArrayIndexOutOfBoundsException if index is negative
//如果index是负数,抛出ArrayIndexOutOfBoundsException
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
} //真正的获取元素的方法,就是从底层的数据库获取index处的元素,返回值E是由ArrayList的泛型指定
E elementData(int index) {
return (E) elementData[index];
}

set(int index, E element)

     public E set(int index, E element) {
//先对角标进行校验,看看是否越界
rangeCheck(index); //取出以前位于该指定位置上的元素
E oldValue = elementData(index);
//将数组位于index位置上的元素设置为element
elementData[index] = element;
//将以前位于该指定位置上的元素返回
return oldValue;
}

 isEmpty()

 public boolean isEmpty() {
//如果ArrayList的size==0,那么即为Empty
return size == 0;
}

indexOf(Object o)

 public int indexOf(Object o) {
//这里对传入的Object进行了一个是否为空的区分
//不管是否为空,都去遍历底层的数组
//如果在数组中得到与传入的Object相等的,则返回该元素在数组中的角标
//否则,返回-1
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
05-07 15:17
查看更多