List.remove() oddities

From reddit’s r/java, a user observed that List.remove(Object) removes the first object whose equals() method returns true. Thus, if two objects have object equality with each other, but you wish to remove the second, you’re going to have to find it and return it with the indexed version of remove(int) instead of the remove(Object) call.

yawkat observed that you can use Collection.removeIf() (which List inherits) and get it done as well:

list.removeIf(o -> o == objectToRemove);

It’d probably still be better to fix equals() so it was more specific, but sometimes your code doesn’t always fit the circumstances you want.

Leave a Reply