• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object Matching on IO

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Alvin Parker
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic