intnumMoved= size - index - 1; if (numMoved > 0) //把删除的位置后一位数据 向前移 System.arraycopy(elementData, index+1, elementData, index, numMoved); //设置原位置元素为null 方便释放内存 elementData[--size] = null; // clear to let GC do its work
publicbooleanremove(Object o) { if (o == null) { for (intindex=0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { //如果有元素值 == o 找到对应的位置 并移除 for (intindex=0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(int index) { modCount++; intnumMoved= size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
ArrayList清空数据 - clear()
1
list.clear()
clear()源码
1 2 3 4 5 6 7 8 9
publicvoidclear() { modCount++;
// 数组内所有元素置null for (inti=0; i < size; i++) elementData[i] = null;
//保存ArrayList中的实例状态到序列中 privatevoidwriteObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff intexpectedModCount= modCount; s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone() s.writeInt(size);
// Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); }
if (modCount != expectedModCount) { thrownewConcurrentModificationException(); } }
// Read in size, and any hidden stuff s.defaultReadObject();
// Read in capacity s.readInt(); // ignored
if (size > 0) { // be like clone(), allocate array based upon size not capacity intcapacity= calculateCapacity(elementData, size); SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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(); } } }