您的位置:首页 > 其它

ArrayList中的remove方法是如何实现的

2013-05-04 18:17 344 查看

ArrayList

remove方法的源码:
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}


首先当然是找到要删除的对象的下标,毕竟在java中List的实现是使用数组来实现的,一个数组,你说要删掉某个元素,那是什么意思,意思就是把要删除元素下标之后的元素都移前一位:
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; // Let gc do its work
}


elementData[--size] = null;把要删除元素之后的元素都前移一位之后,最后一个元素都让要设置为null了

下面是TestSystemCopy.java:
package testSystem;
public class TestSystemCopy {
public static void main(String[] args) {
String[] strArr = new String[]{
"1","2","3",
"4","5","6",
"7","8","9"
};
//把下标为4的元素往前移一位
System.arraycopy(strArr, 3, strArr, 2, strArr.length -3);
strArr[strArr.length-1] = null;
for(int i = 0; i < strArr.length; i++){
System.out.println(strArr[i]);
}

}
}
ArrayList中是使用数组来实现的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ArrayList remove
相关文章推荐