I have a Hashmap that has keys of of type Account (custom class) and the values are strings. The Account class has the following private variables:
1) name (String type)
2) account number (String type)
3) balance (type double).
Following are the files:
When I ran this program, I expected the output to be:
A, 142463, 677489
but, I am getting the following output:
A 14243 46778.0
My understanding was that when a duplicate key is added (as defined in the equals() method) to a hash map, it replaces the old (key,value) pair.
I then recreated the old Account object and tried to get its key value. The output was as below:
A 14243 46778.0
Value for Account c = 23
That is, its keeping the old key (A 14243 46778.0), but replacing its previous value (444) with the value of the newly added Account (23).
Also, when I check for "444" in the map, I am no longer able to obtain the corresponding key as it has been replaced with 23.
I would be grateful in any help in fixing this issue.
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
The problem is that your two values of account claim to be identical (they report "equals" when compared with one another) but that's a lie.
(Notice it says "the old value is replaced")
I'm unclear whether you're trying to solve a problem or understand the API. If the latter, you succeeded already. If the former, you're doing it wrong, but until you tell us what you're actually trying to achieve, we can't be much help telling you how it should be done.
Your equals method does not quite follow the contract specified in Object. It will throw an Exception if Object is not assignable to an Account reference (the cast will fail), but the contract for that method states that it must return false in that situation. The equals method should not throw an Exception for any reason.