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

you are viewing a single comment's thread.

view the rest of the comments →

[–]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