Results 1 to 4 of 4
Thread: hashCode() contract
- 01-14-2011, 10:46 AM #1
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
hashCode() contract
Hi friends
i have a confusion regarding hashCode() contract
the rule says if equals() return true then hashCode() comparison should also return true
but i violate this but no problem in compiling and running
why this code works fine?Java Code:class HashCodeTest1 { int x; int y; HashCodeTest1(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (this.x == ((HashCodeTest1)o).x) return true; return false; } public int hashCode() { return y; } public static void main(String ... args) { HashCodeTest1 obj1 = new HashCodeTest1(10,10); HashCodeTest1 obj2 = new HashCodeTest1(10,20); System.out.println(obj1.equals(obj2)); System.out.println(obj1.hashCode() == obj2.hashCode()); } }
is hashCode() contract is just a specification which is not mandatory?
thanks in advance......
-
Correct. Disobeying this "rule" will not cause a compiler error (indeed there is no way that the compiler could possibly check for all possible infarctions of this rule), but will create a program that can potentially misbehave in pernicious and difficult to detect ways. Disobey this rule at your own peril.
- 01-14-2011, 11:04 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,448
- Rep Power
- 16
If you had a HashMap that used one of those objects as a key you might see problems.
For example:
Java Code:Map<HashCodeTest1, String> map = new HashMap<HashCodeTest1, String>(); HashCodeTest1 myKey = new HashCodeTest1(1,0); HashCodeTest1 myEqualKey = new HashCodeTest1(1,1); map.put(myKey, "Something or other"); if (myKey.equals(myEqualKey)) { // Should be able to use myEqualKey to get the value in the map since they're equal System.out.println(map.get(myEqualKey)); // Uh oh, this is null }
- 01-14-2011, 11:32 AM #4
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
Similar Threads
-
HashCode value of String class Object!
By Anjaneyulu in forum Advanced JavaReplies: 17Last Post: 02-24-2010, 01:49 PM -
hashCode questions
By alpdog14 in forum New To JavaReplies: 3Last Post: 02-19-2010, 11:00 PM -
An acceptable hashcode?
By dsym@comcast.net in forum New To JavaReplies: 7Last Post: 03-29-2009, 09:04 PM -
B2B Technical Lead (Contract to Perm)
By subhasis.patro@gmail.com in forum Jobs OfferedReplies: 0Last Post: 09-19-2008, 07:52 PM -
Why Equals method should be over ridden in Hashcode?
By skyineyes in forum New To JavaReplies: 1Last Post: 05-26-2008, 04:13 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks