This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Let's say that I have a client Socket that sends an object. I read that object using InputStream.readObject();
Now I put that object in a Map as the Map's key. Later the same client outputs the object again but has changed a class member and the server reads the object in again. Will I be able to retrieve the value from the Map by simply passing in the newly read object (Map.get(secondTimeIReadObject)) or do I need to do something more sophisticated in my code?
I know I can test this myself and I will if I get no responses. I'm simply in a hurry to get something done for a customer and so thought I would ask here in case someone knows immediately.
That depends on how the equals method is written. If you haven't written one then the answer is no but you shouldn't be using that object as a Map key anyway if this is the case. If you override the equals method then the result depends on if the value changed is used to calculate equality.
Also you should note that equals may not be the only method involved. If you use a HashMap you will also need to determine how the hashCode is generated. And if you use a TreeMap you need to look at the compareTo method.
It generally is not a good idea to use an object as a key in a map if the contents are allowed to change.
Joined: Oct 01, 2013
Thank you very much Steve.
Since my objects do have two members related to a pool of immutable values (IPAddress and Port), I can compare on those members and safely know that the key I got from the Map is in fact the key I'm looking for (or override the .equals method as you state) so I will do that instead of just relying on the ConcurrentMap to know what I'm asking for.