在上一篇文章中我們分析了ArrayList的構(gòu)造方法和添加方法;
http://www.reibang.com/p/14697d9892b6
這篇文章讓我們來(lái)看看它的移除方法壹将。
ArrayList 總共有3個(gè)移除方法
- 移除指定位置的數(shù)據(jù)
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,就會(huì)報(bào)我們經(jīng)常會(huì)碰到的數(shù)組越界異常齐帚;
下面的代碼就是把index之后的所有數(shù)據(jù)向前移動(dòng)一位追葡,然后把最后一位的數(shù)據(jù)設(shè)置為null喇颁;
- 移除集合中的指定數(shù)據(jù)
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;
}
從第三行的邏輯開始看阱缓,首先判斷要移除的對(duì)象是否為空戳护;
如果不為空金抡,循環(huán)整個(gè)數(shù)組,找到object數(shù)組所在的位置腌且,然后邏輯就跟上面的移除類型梗肝,把object在數(shù)組中所在位置的后面的數(shù)據(jù)向前移動(dòng)一位,并且設(shè)置最后一位為null铺董。
如果為空巫击,就是找到null所在的位置禀晓,和上面的邏輯一致。
從這段代碼可以看出坝锰,ArrayList是允許添加null數(shù)據(jù)的粹懒,在移除的時(shí)候移除null數(shù)據(jù),是移除最前面的null數(shù)據(jù)顷级,找到就return凫乖。
- 移除集合中指定集合的數(shù)據(jù)
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;
}
這個(gè)移除方法并不是ArrayList自己本身的,它是AbstractCollection類的弓颈,那ArrayList和它是什么關(guān)系呢帽芽?ArrayList的父類是AbstractList,而AbstractList的父類是AbstractCollection翔冀,所以ArrayList也是AbstractCollection的子類导街。
這個(gè)方法內(nèi)部實(shí)現(xiàn)是通過(guò)迭代器來(lái)實(shí)現(xiàn)的,循環(huán)遍歷當(dāng)前的集合纤子,如果遍歷得到的數(shù)據(jù)存在于要?jiǎng)h除的collection集合當(dāng)中菊匿,就移除這條數(shù)據(jù)。
ArrayList其它常用方法
- 集合大小
@Override
public int size() {
return size;
}
就是返回標(biāo)示數(shù)量的size字段
- 清空方法
@Override
public void clear() {
if (size != 0) {
Arrays.fill(array, 0, size, null);
size = 0;
modCount++;
}
}
就是把數(shù)組所有項(xiàng)都置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;
}
大致意思就是循環(huán)數(shù)組计福,通過(guò)equals方法尋找相同的對(duì)象,所以要用到這個(gè)方法的話要重寫對(duì)象的equals方法徽职。
- 轉(zhuǎn)化數(shù)組方法
public Object[] toArray() {
. int s = size;
Object[] result = new Object[s];
System.arraycopy(array, 0, result, 0, s);
return result;
}
大致意思就是先new一個(gè)數(shù)組象颖,然后copy數(shù)據(jù)到新數(shù)組。
至此ArrayList的常用的一些方法就分析完了姆钉。