ArrayList.add works, but not ArrayList.remove

Creating an instance of an object (o) and adding it to an Arraylist (arrayList) works fine. However, the delete function does not work.

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

What am I missing?

+4
source share
1 answer

ArrayList.remove() look like this:

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;
}

So, if yours Objecthas a default value equals()then this does not work. The whole object is different. Add equals()to class Object.

+3
source

All Articles