Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Properly overriding equals and hashCode

Andrew Mcmurray
Ranch Hand
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?

Thanks,

AMD

//Item equals and hashCode

//ShoppingCart methods almost the same as above

Jeff Albertson
Ranch Hand
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 ]

Andrew Mcmurray
Ranch Hand
Posts: 188
Thanks Jeff,

Other then that does it look ok?

Thanks,

AMD

Paul Clapham
Sheriff
Posts: 21416
33
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.