底层的数组对象
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. Any 4 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to 5 * DEFAULT_CAPACITY when the first element is added. 6 */ 7 //ArrayList底层的数组对象 8 private transient Object[] elementData;
get(int index) 方法
1 public E get(int index) { 2 //先对角标进行校验,看看是否越界 3 rangeCheck(index); 4 5 return elementData(index); 6 } 7 8 //throws an ArrayIndexOutOfBoundsException if index is negative 9 //如果index是负数,抛出ArrayIndexOutOfBoundsException 10 private void rangeCheck(int index) { 11 if (index >= size) 12 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 13 } 14 15 //真正的获取元素的方法,就是从底层的数据库获取index处的元素,返回值E是由ArrayList的泛型指定 16 E elementData(int index) { 17 return (E) elementData[index]; 18 }
set(int index, E element)
1 public E set(int index, E element) { 2 //先对角标进行校验,看看是否越界 3 rangeCheck(index); 4 5 //取出以前位于该指定位置上的元素 6 E oldValue = elementData(index); 7 //将数组位于index位置上的元素设置为element 8 elementData[index] = element; 9 //将以前位于该指定位置上的元素返回 10 return oldValue; 11 }