简体   繁体   中英

Does the not overriden toString() method always return same value for object?

I have two classes(fe Car and Bicycle). Objects of both classes are sent to management layer, where they are used. I send every object to that layers by calling layerHandler.objectReceived(object);

LayerHandler then need to store this object in its HashMap (im using Object because objects which will be stored there are not same type...(Car and Bicycle))

LayerHandler has other method called actionFired(String message, Object object); Second parameter 'object' belongs to Car or Bicycle class and is already stored in LayerHandler's HashMap. When this method occures, I need to find related object which is stored in HashMap.

Right now Im using object.toString() as key value for hashmap. Both type of objects use defaut toSting() method which is not overriden.

Im not going to show whole structure of my project here, but Im using HashMap for a reason. (I know ArrayList get(Object obj) method would be nice here, but I must use HashMap)

I need to know, whether toString() will always returns same value which wont change over time so I will be able to use that as a key for my HashMap.

If you haven't overridden .toString() then, for a given instance, it will continue to return the same string throughout the instance's life. But it is quite possible that once this instance has been garbage collected, another instance of this class or even another class will be allocated to the same block of memory and will return the same string as this one did.

But rather than using a String as the key, you would be better off changing actionFired to give you the object rather than a string representation. It's very fragile to do it like this, and if your implementation changes later, it might all break.

There is no restrictions to have different types of keys in the HashMap, if you provide correct implementation of hashCode+equals.

  1. You should override hashCode+equals methods in your key-object classes (Car, Bicycle, ...)
  2. Use these objects directly as keys in your HashMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM