2

Why is the output of this program false? I am expecting true as n object initialize with same string what I am checking for.

public class Test {
    public static void main(String[] args) {
        Name n = new Name("jyoti", "meher");
        Set<Name> s = new HashSet();
        s.add(n);
        System.out.println(s.contains(new Name("jyoti", "meher")));
    }
}

class Name {
    String name, title;

    public Name(String name, String title) {
        this.name = name;
        this.title = title;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Name)) {

            return false;
        }
        Name n = (Name) o;
        return n.name.equals(name) && n.title.equals(title);
    }
}
loknath
  • 1,322
  • 15
  • 24

5 Answers5

11

You have to override hashCode() too, not just equals().

Gabriel Negut
  • 12,932
  • 3
  • 34
  • 43
4

To get the correct output true you need to override the hashCode() method in the Name Class

Edd
  • 3,510
  • 3
  • 23
  • 33
loknath
  • 1,322
  • 15
  • 24
2

If two objects have different hashCode values then they will be considered not equal by a HashSet.

Whenever you override equals you should also override hashCode() to ensure it is consistent. This is particularly important when dealing with HashSet and HashMap which rely on the hash code to distribute objects.

You can make your code work with the following (non-optimal) implementation of hashCode:

@Override
public int hashCode() {
    return 1;
}

This will force the HashSet to use your equals() method when comparing your Name objects. If you used both name and title when generating the hash code then there would be less occasions when the equals method would have to be used.

Richard Miskin
  • 1,230
  • 7
  • 12
1

In the Name class both equal and hashcode method should override.so that output will be true.

0

You should override equals() and hashcode() method to ensure the contract is satisfied to use your object as a key in the implementations like HashSet and HashMap.

You have overridden equals correctly. You can override hashcode also like below

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((name == null) ? 0 : name.hashCode());
    result = prime * result + id;
    result = prime * result
            + ((title == null) ? 0 : title.hashCode());
    return result;
}  

Overriding hashcode facilitates your object to be stored in different slots based on the hashcode which makes your search faster.

Hope this helps

Srikanth Ganji
  • 1,067
  • 1
  • 11
  • 27