Search code examples
androidkotlincollectionscontains

Contains method returns always false?


i am fetching contacts and adding to a list.list contains duplicate contacts too,i have to remove duplicate contacts at the time of adding to list.

i am using contains method at the time of adding to list but contains method always returns false even there is same element in list.

if (!phoneContactVOList.contains(contactVO)) {
    contactVO.ContactName = name
    contactVO.ContactNumber = phoneNumber

    phoneContactVOList.add(contactVO)
}

here above code i am trying to add only unique contacts in list but duplicate contacts also adding.


Solution

  • You need to override the equals(...) method and write your custom implementation that returns true if the name and the phoneNumber are the same. For example like this:

    override fun equals(other: Any?): Boolean {
               if(other == null || other !is ContactClassObject)
                   return false
               return name == other.ContactName && phoneNumber==other.phoneNumber
            }