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