Reputation: 10132
I have below code and I have placed break points on overridden equals()
and hashCode()
methods of ContainerBean
. When I run below application in debug mode, debugger stops at hashCode()
only for System.out.println
line and not while trying to remove element from List
.
import java.util.ArrayList;
import java.util.List;
public class ListRemovalDriver {
public static void main(String[] args) {
List<ContainerBean> remitClaims = new ArrayList<>();
ContainedBean addedRemit1 = new ContainedBean();
addedRemit1.setRemitId(12345L);
ContainerBean added1 = new ContainerBean();
added1.setRemitBean(addedRemit1);
remitClaims.add(added1);
ContainedBean removedRemit1 = new ContainedBean ();
removedRemit1.setRemitId(12345L);
ContainerBean removed1 = new ContainerBean ();
removed1.setRemitBean(removedRemit1);
System.out.println("List before valid removal" + remitClaims);
remitClaims.remove(removed1);
System.out.println("List after valid removal" + remitClaims);
}
}
Am I missing something?
Would overridden equals()
in ContainerBean
not be called while removing element from list?
EDIT
I forgot to mention that hashCode()
and equals()
are working as expected i.e. elements getting removed as per equals()
logic but its only debugger that is not taking me there on list remove function call.
Upvotes: 0
Views: 1309
Reputation: 22412
Would overridden equals() in ContainerBean not be called while removing element from list ?
Yes, when you are using remove(Object o)
, then equals()
in ContainerBean
will be called to check the equality of the object and then remove it from the list as mentioned in the ArrayList
API below (emphasis mine):
Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
But, on the other side, when you are removing an element using the index of the list (i.e., using remove(int index)
), then there will NOT be any equals()
check.
You can look here
Upvotes: 1
Reputation: 14149
Since you did not give the code I have to guess: You did not override equals, but instead added an overload like this:
public boolean equals(ContainerBean c) { ... }
This will not work because equals(Object) is called.
Change your equals implementation to take an argument of type Object and it will both get called and stopped at in eclipse debugger.
Upvotes: 2
Reputation: 70
Source code of ArrayList from jdk 7,
ArrayList.remove(Object o)
it invokes equals method to verify the object to remove from the collection
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
source: ArrayList Source
Upvotes: 1