1

I have this method:

private static void searchChannelByName(String name, ArrayList<VeediChannel> channel,HashSet<VeediChannel> newChannelsList)
{
    if(channel!=null) {
        for (int i = 0; i < channel.size(); i++) {
            if (channel.get(i).getName().toUpperCase().contains(name))
                newChannelsList.add(channel.get(i));
        }
    }
}

I want to override to set the logic in which the set add is done (for preventing duplicates) so in VeediChannel class i am doing this:

@Override
public boolean equals(Object o)
{
    Log.i(Utils.TAG,"In equals");
    if(this.getName().equals(((VeediChannel) o).getName()))
        return true;
    else
        return false;
}

So when the add method is called on the newChannelsList the equals is supposed to be called

but, when checking the logs the equals method dont get call at all What seems to be the problem?

Michael A
  • 5,770
  • 16
  • 75
  • 127

3 Answers3

2

If you override equals without overriding hashCode, the add method of HashSet may look for the added element in the wrong bucket, and if there are no entries in that bucket, equals will never be called.

Even if you overridden both equals and hashCode, it's possible that equals won't be called when adding elements to the HashSet, if there are no duplicates and each element happens to be mapped to a different bucket.

Your hashCode implementation must be compatible with the equals implementation. For example:

@Override
public int hashCode ()
{
    return getName().hashCode();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

You are adding to a HashSet, which does not normally use equals unless there is a collision. It looks like for the set you are constructing, there are no collisions, which means that the default hashing algorithm is using its job.

However, you will want to override your hashCode method in addition to equals. The basic requirement is that two equal object must have the same hash value. A simple implementation that satisfies this condition is

@Override
public int hashCode()
{
    Log.i(Utils.TAG,"In hashCode");
    return this.getName().hashCode();
}
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

As mentioned in comment, you must override hashCode() as well. Here's a good detailed answer on this theme: https://stackoverflow.com/a/27609/3941803

Community
  • 1
  • 1
Taras
  • 105
  • 1
  • 7