I am learing about HashMaps and I am stuck on the following scenerio.
Lets say I have an Employee class with the following instance variables.
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?