This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
I have a class Item which has the following information.
public class Item { protected String mName;//name of the item, e.g. "Effective Java" protected double mPrice;//price e.g. "40.4" protected String mType;//type e.g. "Book" }
I need to store Item in Map, hence I am overriding hashCode() and equals() methods. I know how to write both of them. My question is , what members should I use in the equals() method.
Should I use ALL the three members mName, mPrice and mType or will mName and mType suffice. Reason being the price of the Item which will change during application as below:
e.g. Item book = new Item("Effective Java", "45.5", "Book"); Map map = new HashMap(); map.put(book, qty). double shipment = calculateShipment(book); //Here price of the book changes. book.setPrice(shipment);
I know this is more of a design question, but in general how do we decide what are the member variables we use in equals() and hashCode(). Please answer wrt this example.
Thanks
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
From the API for Object.hashCode:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
So if the price is going to change during a run of the program, I think it would be unwise to use it in the combined hash, or in the equals comparison. [ December 27, 2004: Message edited by: Barry Gaunt ]
when are two Books the same ? if they have the same title, i would say (ok, in the real world you would probaby use the ISBN number or something like that).
when are two Items the same ? if they have the same type and the same title. so i would include title and type in both, hashCode() and equals()
pascal
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.