Hi,
According to the Object API, the method hashCode should return the same hash for two instances of a class for which the equal function returns true, i.e. when a.equals(b), (a.hashCode() == b.hashCode) should be true. I've created a test case where this statement does not hold:
package test;
public class Test {
public static void main (String [] args) {
TestSave s = new TestSave("Hi");
System.out.println(s.hashCode() + "");
TestSave j = new TestSave("Hi");
System.out.println(j.hashCode() + "");
System.out.println(s.equals(j));
}
}
class TestSave {
private final String something;
public TestSave (String something) {
this.something = something;
}
public boolean equals (Object o) {
if (o instanceof TestSave) {
TestSave oo = (TestSave) o;
return oo.something.equals(something);
}
return false;
}
}
When running the program, the output is:
12133390
10053659
true
Is it my responsibility to provide my classes with a decent implementation of the hashCode method? What are your thoughs on this?