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?
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 ]
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.