File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Properly overriding equals and hashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Properly overriding equals and hashCode" Watch "Properly overriding equals and hashCode" New topic

Properly overriding equals and hashCode

Andrew Mcmurray
Ranch Hand

Joined: Sep 24, 2005
Posts: 188
Hi all ,

I have been seeing some stuff on how important it is to properly override the equals and hashCode methods and how most of the time people do it wrong. I want to make sure I am doing it right, right meaning conforming to the general contract of the equals and hashCode methods.

I have two classes Item and ShoppingCart. Item is considered equal if the description and cost are the same and Shopping Cart is considered equal both carts contain the exact same items. Here are my overriden equals and hashCode methods. Let me know if they look ok or that they need some fixing?



//Item equals and hashCode

//ShoppingCart methods almost the same as above
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
If items is a List, you can use equals. See the definition of List's equals method:

What is cost's type? It looks like it may be float or double. Realize that storing currency in a floating point type is always asking for trouble because of rounding. Consider storing it in an integer type (cents or tenths of cents, etc...) or using BigDecimal or your own custom class. Back to float/double: do you know they have one last trick up there sleeve? floating point numbers can take on the value NaN (not a number) which doesn't obey the usual rules of the relational operators, for example, Double.Nan == Double.NaN is false! Of course, your cost probably never takes on that value, but the paranoid code for that in equals/hasCode.
[ February 03, 2006: Message edited by: Jeff Albertson ]

There is no emoticon for what I am feeling!
Andrew Mcmurray
Ranch Hand

Joined: Sep 24, 2005
Posts: 188
Thanks Jeff,

Other then that does it look ok?


Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

I think your ShoppingCart's hashCode() method returns different values for two objects whose items are the same overall but in different orders. But then its equals() method returns false for two such lists, so technically that is okay.
I agree. Here's the link:
subject: Properly overriding equals and hashCode
It's not a secret anymore!