privatevoidrangeCheckForAdd(int index){ if (index > size || index < 0) thrownew IndexOutOfBoundsException(outOfBoundsMsg(index)); }
ArrayList获取数据 - get()
1
list.get(0);
get()源码
1 2 3 4 5 6
public E get(int index){ //判定index位置是否在范围内 rangeCheck(index);
return elementData(index); }
ArrayList删除数据 - remove()
1 2 3
list.remove(0); //删除内容 list.remove("Android")
remove(int index)源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public E remove(int index){ //检查index有没有超出范围 rangeCheck(index);
modCount++; //保存需要删除的数据 可以返回旧值 E oldValue = elementData(index);
int numMoved = 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 (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { //如果有元素值 == o 找到对应的位置 并移除 for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(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 }
ArrayList清空数据 - clear()
1
list.clear()
clear()源码
1 2 3 4 5 6 7 8 9
publicvoidclear(){ modCount++;
// 数组内所有元素置null for (int i = 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 int expectedModCount = 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) { thrownew ConcurrentModificationException(); } }
// 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 int capacity = 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(); } } }