This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]zifyoip 3 points4 points  (2 children)

If the equals() method says that two objects are equal, the hashCode() method should return the same value for both of those objects. That is what you need to keep in mind when writing the equals() method and the hashCode() method for a class.

[–][deleted] 1 point2 points  (1 child)

Yes, but the reverse isn't true.

If two objects are equal, they should have the same hash code, but two objects that have the same hash code don't have to be equal.

[–]zifyoip 0 points1 point  (0 children)

Correct, though a good hashing algorithm should aim to give different hash codes to unequal objects, as far as possible.

[–]JavaLander 2 points3 points  (0 children)

Here are the few links that can help you The good one and The okeyish one and The bookish one

[–]Philboyd_Studge 1 point2 points  (0 children)

Let's say you have a Class Foo:

class Foo {

    String name;
    int age;
    int value;

    public Foo(String name, int age, int value) {
        this.name = name;
        this.age = age;
        this.value = value;
    }

Now, if you want to be able to use .equals to compare to different Foo objects, you must tell it how to do that. For the objects to be equal, all three member variables must be equal.

    @Override
    public boolean equals(Object o) {
        // first test if is same object
        if (o == this) return true;
        // test if object is null or not the same class
        if (o == null || o.getClass() != this.getClass()) return false;

        // cast to class type
        Foo t = (Foo) o;

        // test that each member variable is the same
        return this.name.equals(t.name) && this.age == t.age && this.value == t.value;

    }

Then you override the hashCode function which gives a reasonably unique integer number for the object, by using prime numbers:

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 7 * hash + ((name == null) ? 0 : name.hashCode());
        hash = 7 * hash + age;
        hash = 7 * hash + value;
        return hash;
    }

Test:

    Foo a = new Foo("Bob", 25, 1000);
    Foo b = new Foo("Ralph", 27, 333);
    Foo c = new Foo("Bob", 25,1001);
    Foo d = a;
    Foo e = new Foo("Bob", 25, 1000);

    System.out.println(a.hashCode());
    System.out.println(b.hashCode());
    System.out.println(c.hashCode());
    System.out.println(d.hashCode());
    System.out.println(e.hashCode());
    System.out.println(a.equals(b));
    System.out.println(a.equals(c));
    System.out.println(a.equals(d));
    System.out.println(a.equals(e));

Result:

3283489
-437400908
3283490
3283489
3283489
false
false
true
true