Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

hashCode not the same for equal objects

807591Feb 26 2008 — edited Mar 4 2008
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?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 1 2008
Added on Feb 26 2008
31 comments
876 views