Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and hashcode() contracts

 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey while going through one post i got one doubt....is it neccessary that we should use the same variables to implement equals() and hsahscode() methods.


Is it specifically mentioned in the contract that we should use the same variable for both hashcode() and equals() method.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sanjit Kumar:
hey while going through one post i got one doubt...

I'm afraid that other post is something I said that's probably misleading.

No, it's not required that these methods use the same variables. But if they don't, you need to be very careful. I just posted a follow-up response under that other topic, so see if that clears it up.

Sorry for the confusion.
 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks marc for the quick reply,

the concept i know is as follows:
1> if a.equals(b) is true then it must be consistent meaning it should always give the same result unless.

2> if a.equals(b) is true then b.equals(a) should also be true.

3> if a.equals(b) true then hashcode() for both object must be same.

4> if a.equals(b) is not true then hashcode for both object may or may not be equal.

If anyhting wrong in above concpet please correct me and mention if something more is required.

thanks
 
Henry Wong
author
Marshal
Pie
Posts: 21000
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sanjit Kumar:
thanks marc for the quick reply,

the concept i know is as follows:
1> if a.equals(b) is true then it must be consistent meaning it should always give the same result unless.

2> if a.equals(b) is true then b.equals(a) should also be true.

3> if a.equals(b) true then hashcode() for both object must be same.

4> if a.equals(b) is not true then hashcode for both object may or may not be equal.

If anyhting wrong in above concpet please correct me and mention if something more is required.

thanks


There are a few more to remember...

5. a.equals(a) must always be true.

6. if a.equals(b), and b.equals(c), then a.equals(c) must always be true.

7. a.equals(null) must always be false.

Okay, most of these points are "obvious conclusions" from the other four. However, they are mentioned in the specification, so they may come up in the exam.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic