0

So for a long time i thought that objects are compared using equals() which uses hashcode() , which means if 2 objects have same hash code it returns true.

The equals() method from source code:

@see java.lang.System #identityHashCode
public boolean equals(Object obj) {
        return (this == obj);
    }

So i created this:

public static void main(String[] args) {
        Dog rover = new Dog("Rover");
        Dog german = new Dog("Rover2");

        System.out.println("German: " + german + "\tRover: " + rover);
        System.out.println(german.equals(rover));


    }

Also i overridden the hashCode() to:

    @Override
    public final boolean equals(Object obj) {
        if (this == obj)
            return true;
    }

    @Override
    public int hashCode() {
        //The main point of 0 is to check how equals actually work
        return 0;
    }

Now the print statement is printing false even both objects are @Dog0. Wondering why Console:

German: Animal.Dog@0    Rover: Animal.Dog@0
false
Bishop
  • 3
  • 3

2 Answers2

1

The reason they are not "equal" has nothing to do with hash codes.

The reason they are not equal is this condition:

this == obj

which returns true only if obj is the same object as this.
You have 2 objects, so that can't be true.

Also, as you can see from the source code, calling equals() does not call hashCode(). AFAIK, there's no implementation (in the JDK anyway) where equals() calls hashCode().

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Maybe the confusion arose because how `Object`'s `toString()` is implemented. It prints: `getClass().getName() + '@' + Integer.toHexString(hashCode())` and `Òbject`'s default `hashCode()` implementation converts object's **internal address** into an integer. This internal address is also what the `==` operator is using, hence the confusion. – Janez Kuhar Oct 14 '17 at 17:49
  • Maybe its worth to add this to your answer: equals() and hashCode() are tied together by contract: If o1.equals( o2) returns true then o1.hashCode() == o2.hashCode must be true as well. The opposite is not always true: Two objects can have the same hash code, but equals may nevertheless return false (i.e. with very big strings). – Heri Oct 14 '17 at 20:15
1

You are using equals as an "alias" for the this == obj comparison which is wrong and that's why it doesn't work.

Objects have the equals method because this == obj only returns true if it is actually the very same object (same reference in memory).

What you need to do is manually compare the properties in the equals method and only return true if they match.

techfly
  • 1,826
  • 3
  • 25
  • 31
  • So when dealing with objects it looks on memory address rather than hashcode to return a true? – Bishop Oct 14 '17 at 17:48
  • Yes, exactly. It looks if you are "pointing" to the same object and has nothing to do with hashcode. – techfly Oct 14 '17 at 17:48