Search an ArrayList for a particular Object

前端 未结 6 840
陌清茗
陌清茗 2021-01-21 07:05

I have a class called Person. It has the following attributes; It has 2 attributes, ID, and Telephone. 1 person can have many

6条回答
  •  花落未央
    2021-01-21 07:31

    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.

提交回复
热议问题