/** * 遍历数组,找出需要删除的元素的索引,并调用删除方法 */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { //具体删除方法 fastRemove(index); returntrue; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }/** * 删除指定索引的元素 * */ 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; } /* * 删除指定元素 */ private void fastRemove(int index) { modCount++; 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 }复制代码
需要注意的是删除一个元素也是通过底层的方法实现的。
接着看get和set相对就比较简单了。
1234567891011121314151617181920复制代码
public E get(int index) { //判断索引是否越界 rangeCheck(index); return elementData(index); } /** * 判断索引是否越界 */ private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } public E set(int index, E element) { //判断索引是否越界 rangeCheck(index); //获取此索引原先的值 E oldValue = elementData(index); elementData[index] = element; return oldValue; }复制代码
/** * 将List写入s,注意先写容量,然后在写数据 * @param s * @throws java.io.IOException */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // 首先写数组容量 s.writeInt(size); // 遍历写数组中的元素 for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * 读取s中的List */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // 首先读数组容量 s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } }复制代码