This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
As I instantiate Employee objects I want to store them in a HashMap. The keys for the map will be the int value computed by the hashCode() method of an Employee object, and the value will be a reference to the Employee object. According to K&B I should override equals() and hashCode(). Also, according to K&B, since my equals() method compares the above attributes of 2 Employee objects to determine equivalent objects, my hashCode() method should use these same instance variables to compute the hashcode.
Now at some later date I want to retrieve a value from the HashMap. In order to do this, I need the key of the key-value pair. But since the key is an int value derived from the hashCode() of the Employee object I must have access to the object’s instance variables in order to compute the key’s value. But, if I have access to the object’s instance variables in the first place, then it seems that the purpose of the HashMap data structure is defeated.
If I were to use a subset of the instance variables (like lastname) in my hashcode calculation then using HashMaps seems more useful, since a value like a lastname can be easily obtained. But this would seem to contradict what K & B says about using all the instance variables for the hashcode calculation.
I also thought about adding a unique numeric value like employee code to the class which I could then use this as the key for my hashmap. But this has implications for my equals() method. I am thinking that I might need to change it to reflect that 2 equal employee code numbers imply equal Employee objects.
As you can see I am in a bit of a quandry. I guess what I need is a real world example on hashmaps. All the examples I have found are unrealistic and use integer values like 1,2,3 for keys. Does anyone know of a good example on hashmaps?
IMO, if you need to select a key, you probably don't need a map. Maps are good at holding relationships, a mapping between keys and values. If all you have are values, and you need to find keys so it can be stored, it may be better to use a set or a list instead.
Also, you mentioned using the hashCode as the key for the map. That is unsafe since two unequal objects may have the same hashCode (the only requirement for hashCode is that two equal objects must have the same hashCode).
To add a little more detail on HashMaps, as Henry stated, they are really used for key-value relationships. An example in your Employee class would be using a social security number (since it is unique) for the key. Then if someone gives you an SSN, you can lookup the employee based on it.