Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes I/O and Streams and the fly likes Object Matching on IO Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Object Matching on IO" Watch "Object Matching on IO" New topic
Author

Object Matching on IO

Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
I have a general question about Object.equals.

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.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
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.
 
wood burning stoves
 
subject: Object Matching on IO