• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overridding hashcode and equals versus implementing Comparator/Comparable interface  RSS feed

 
Suhaas Mohandos
Greenhorn
Posts: 21
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My question is on what basis I have to override hashcode and equals methods and when to implement the Comparator/Comparable interface.

To rephrase the question how will I decide whether I have to implement hashcode and equals method or I need to implement Comparator/Comparable interface.

Sorry if the question is not clear.

Regards
Suhaas
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Simply, if instances of your class needs to be checked for equality, and the default is not correct, then you need to override the equals() method.

If instances of your class needs to be placed in hashing collections, then you need to override equals() / hashCode() methods.

If instances of your class needs to be sorted / placed in sorted collections, and have a natural order, then you should implement the Comparable interface. Alternatively, the Comparator interface can also be implemented, but that may be done externally if your class has the capability to access the data needed to compare.


... and ... if you don't know how your class will be used, which I speculate is why you are asking, then I guess you can ask around (or take a guess... ).

Henry
 
Dave Tolls
Ranch Foreman
Posts: 3068
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and if you plan on using them within a TreeSet, which is an ordered Set, then you need to supply a Comparable/Comparator and have the equals (and hence hashcode) methods, and they must be consistent.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To expand what Dave said, the compareTo() method should be consistent-with-equals (unless you have a very good reason not to, e.g. BigDecimal). This is a term that is often used in the standard API, and means that when the equals() method returns true, the compareTo() method must return 0, and when the equals() method returns false, the compareTo() method must return something other than 0.

You can actually implement equals() by doing a type-check first, and then returning whether compareTo() returns 0:
 
Liutauras Vilda
Sheriff
Posts: 4927
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Expanding on Stephan's given code example...

Since Java 1.7 you can validate parameters as such:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!