创建对象实例 (o) 并将其添加到数组列表 (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
类。
关于java - ArrayList.add 有效,但 ArrayList.remove 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984527/