I have a class called Person
. It has the following attributes
; It has 2 attributes, ID
, and Telephone
. 1 person can have many
Many solutions, define two persons as equal by their phone number but what if two persons that live in the same house and / or have the same phone number are added to the list? Which one is the correct one?.
Before rushing to find the person, you have to define a way to determine if two persons are, indeed, equal without ambiguous results. Unless you restrict the creation of persons based on that very phone number by making it unique (you do not clarify this in your question, so I assume there is no such restriction), the result of the search is undefined.
You're using an ArrayList
so you can't guarantee even a result by insertion order.
I suggest you base the equality test in a person's ID
instead of its phone. To prevent the modification of id
's just define a getter for it and do not define a setId
method at all. Then, you can redefine equals
(and hashcode
if you feel like it) based on id
.