[Solved] Java List not contains object [closed]


Your attempt won’t work since you’re handling the creation in the loop, so you will end up adding several persons there.

Just write it the way you described it:

if (allPersons.isEmpty() || !allPersons.contains(person))
  allPersons.add(person)

Now, in order for this to work you have to ask yourself an important question: What exactly constitutes “the same person”?

You described it as same first name/last name, so make sure your equals and hashcode methods are implemented as such. Probably that’s a simplificiation, but the rules still apply. When describing an entity, always thing about what uniquely identifies that entity, and use that for implementing equals and hashcode.

Secondly, since allPersons can’t possibly contain the same person twice, it is a Set, not a List. In that case you can even ditch the check, because the set will automatically make sure only one copy is present.

Third, the check for emptyness is superfluous. Obviously if it’s empty, contains will always be false.

solved Java List not contains object [closed]