簡體   English   中英

ArrayList.add有效,但不是ArrayList.remove

[英]ArrayList.add works, but not ArrayList.remove

創建一個對象(o)的實例並將其添加到Arraylist(arrayList)工作正常。 但是,刪除功能不起作用。

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類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM