我們根據List中的源碼分析,
remove方法的原理:
public boolean remove(Object o){
if(o ==null) {
for(intindex=0;index< size;index++)
if(elementData[index] ==null) {
fastRemove(index);returntrue;
}
}else{
for(intindex=0;index< size;index++)
if(o.equals(elementData[index])) {
fastRemove(index);returntrue;
}
}
return false;
}
List在刪除對象時,先判斷這個對象是否在自己的隊列中?而這種判斷指的是是否equals;
因此,List在刪除對象時,如果使用刪除對象方法,應該最好重寫equals方法。或者采用刪除下標的方法。
刪除下標時一定要確保下標的類型是int類型,若是Integer類型,List會默認匹配remove(Object o)方法,而不是remove(int index)方法。
這是一個在上一個項目中遇到的問題。