I want to find a LegalEntity object in an ArrayList. The object can possibly be a different instance. I'm only interested in whether they represent the same value, i.e. they have the same primary key. All LegalEntity instances are created from database values by EJB:
List<LegalEntity> allLegalEntities = myEJB.getLegalEntityfindAll());
LegalEntity currentLegalEntity = myEJB.getLegalEntityfindById(123L);
My first naive idea never finds matches:
if (allLegalEntities.contains(currentLegalEntity)) {
}
I then thought that perhaps I need to create my own equals() method:
public boolean equals(LegalEntity other) {
return legalEntityId.equals(other.legalEntityId);
}
But this method is not even being invoked. Is there a way to find an object in a list that doesn't involve looping?
I'm learning Java so it might easily be some foolish misunderstanding on my side.
public boolean equals(Object other)and define there what equality means in that case (you mentioned same primary key).contains()does useequals(Object), yourequals(LegalEntity)is notequals(Object). Even so, overridingequals(Object)may not be the correct option, as equality is a difficult concept. You could just write a helper method with a for-loop in it to find it. You didn't really take the easy road in learning Java from EJB and Java 6.public boolean equals(Object other)it appears to work (Objectdoesn't have alegalEntityIdproperty but I can force a cast inside the method). What edge cases can possibly bite my foot in the future?