When I compile and run the code below, I get the following results:
o1==o2 ? true
Hash codes: 0 | 0
o1==o2 ? true
Hash codes: 1 | 8
o1==o2 ? true
Hash codes: 7 | 3
o1==o2 ? true
Hash codes: 68 | 10
o1==o2 ? true
Hash codes: 5 | 4
From what I've read, if two objects are equal, their hashCodes must also be equal. So, how does this code not cause an exception or error?
import java.io.*;
import java.lang.*;
public class EqualsAndHashCode {
private int num1;
private int num2;
public EqualsAndHashCode(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public static void main(String[] args) {
for (int x=0; x < 5; x++) {
EqualsAndHashCode o1 = new EqualsAndHashCode(x, x);
EqualsAndHashCode o2 = new EqualsAndHashCode(x, x);
System.out.println("o1==o2 ? " + o1.equals(o2));
System.out.println("Hash codes: " + o1.hashCode() + " | " + o2.hashCode());
}
}
public boolean equals(Object o) {
return (this.getNum1() == ((EqualsAndHashCode)o).getNum1()) && (this.getNum2() == ((EqualsAndHashCode)o).getNum2());
}
public int hashCode() {
return (int)(this.getNum1() / Math.random());
}
public int getNum1() { return num1; }
public int getNum2() { return num2; }
}
EDIT I The premise behind my question was the wording surrounding the hashCode contract (http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode()):
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
I assumed that this rule would have been enforced by the JVM at compile or run time and I would have seen errors or exceptions right away when the contract was violated...
equalsandhashCodeon any object in the environment during the application run? What if the calculations for equality have nontrivial implementations and consume a lot of CPU time? - Tom G