在上一篇文章中我們分析了ArrayList的構造方法和添加方法;
http://www.lxweimin.com/p/14697d9892b6
這篇文章讓我們來看看它的移除方法。
ArrayList 總共有3個移除方法
- 移除指定位置的數據
public E remove(int index) {
Object[] a = array;
int s = size;
if (index >= s) {
throwIndexOutOfBoundsException(index, s);
}
@SuppressWarnings("unchecked") E result = (E) a[index];
System.arraycopy(a, index + 1, a, index, --s - index);
a[s] = null; // Prevent memory leak
size = s;
modCount++;
return result;
}
首先如果index >= s,就會報我們經常會碰到的數組越界異常;
下面的代碼就是把index之后的所有數據向前移動一位,然后把最后一位的數據設置為null;
- 移除集合中的指定數據
public boolean remove(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
System.arraycopy(a, i + 1, a, i, --s - i);
a[s] = null; // Prevent memory leak
size = s;
modCount++;
return true;
}
}
} else {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
System.arraycopy(a, i + 1, a, i, --s - i);
a[s] = null; // Prevent memory leak
size = s;
modCount++;
return true;
}
}
}
return false;
}
從第三行的邏輯開始看,首先判斷要移除的對象是否為空;
如果不為空,循環整個數組,找到object數組所在的位置,然后邏輯就跟上面的移除類型,把object在數組中所在位置的后面的數據向前移動一位,并且設置最后一位為null。
如果為空,就是找到null所在的位置,和上面的邏輯一致。
從這段代碼可以看出,ArrayList是允許添加null數據的,在移除的時候移除null數據,是移除最前面的null數據,找到就return。
- 移除集合中指定集合的數據
public boolean removeAll(Collection<?> collection) {
boolean result = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (collection.contains(it.next())) {
it.remove();
result = true;
}
}
return result;
}
這個移除方法并不是ArrayList自己本身的,它是AbstractCollection類的,那ArrayList和它是什么關系呢?ArrayList的父類是AbstractList,而AbstractList的父類是AbstractCollection,所以ArrayList也是AbstractCollection的子類。
這個方法內部實現是通過迭代器來實現的,循環遍歷當前的集合,如果遍歷得到的數據存在于要刪除的collection集合當中,就移除這條數據。
ArrayList其它常用方法
- 集合大小
@Override
public int size() {
return size;
}
就是返回標示數量的size字段
- 清空方法
@Override
public void clear() {
if (size != 0) {
Arrays.fill(array, 0, size, null);
size = 0;
modCount++;
}
}
就是把數組所有項都置null
- 包含方法
public boolean contains(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
return true;
}
}
} else {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
return true;
}
}
}
return false;
}
大致意思就是循環數組,通過equals方法尋找相同的對象,所以要用到這個方法的話要重寫對象的equals方法。
- 轉化數組方法
public Object[] toArray() {
. int s = size;
Object[] result = new Object[s];
System.arraycopy(array, 0, result, 0, s);
return result;
}
大致意思就是先new一個數組,然后copy數據到新數組。
至此ArrayList的常用的一些方法就分析完了。