4
創建一個對象(o)的實例並將其添加到Arraylist(arrayList)工作正常。但是,刪除功能不起作用。ArrayList.add工作,但不是ArrayList.remove
arrayList.add(o); // works
arrayList.remove(o); // does nothing
我在想什麼?
創建一個對象(o)的實例並將其添加到Arraylist(arrayList)工作正常。但是,刪除功能不起作用。ArrayList.add工作,但不是ArrayList.remove
arrayList.add(o); // works
arrayList.remove(o); // does nothing
我在想什麼?
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;
}
因此,如果您Object
有默認equals()
,那麼這個斜面工作。所有對象都是不同的。將equals()
添加到您的Object
課程中。
'o'類實現'equals'嗎?請參閱[這裏](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)) – Vidya
請在一般情況下爲語言添加標籤提問。 – Rndm
我們需要更多信息。 @Vidya說它應該實現平等,這是事實。另外,如果你使用整數,你可能會得到不正確的行爲;) –