【问题标题】:ArrayList.add works, but not ArrayList.removeArrayList.add 有效,但 ArrayList.remove 无效
【发布时间】:2013-11-27 20:51:36
【问题描述】:

创建对象的实例 (o) 并将其添加到 Arraylist (arrayList) 工作正常。但是,删除功能不起作用。

arrayList.add(o); // works
arrayList.remove(o); // does nothing

我错过了什么?

【问题讨论】:

  • o 的类是否实现了equals?见here
  • 请在提问时为一般语言添加标签。
  • 我们需要更多信息。 @Vidya 说它应该实现equals,这是真的。此外,如果您使用整数,您可能会得到不正确的行为;)

标签: java object arraylist


【解决方案1】:

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 类中。

【讨论】:

    猜你喜欢
    • 2017-01-08
    • 2012-05-08
    • 2017-03-15
    • 2014-10-30
    • 2011-03-08
    • 2010-11-29
    • 2017-12-13
    • 2015-01-05
    • 2021-06-29
    相关资源
    最近更新 更多