I have two kinds of objects in my application where every object of one kind has exactly one corresponding object of the other kind.
The obvious choice to keep track of this relationship is a Map<type1, type2>
, like a HashMap. But somehow, I'm suspicious. Can I use an object as a key in the Map, pass it around, have it sitting in another collection, too, and retrieve its partner from the Map any time?
After an object is created, all I'm passing around is an identifier, right? So probably no problem there. What if I serialize and deserialize the key?
Any other caveats? Should I use something else to correlate the object pairs, like a number I generate myself?
.equals()
and .hashCode()
correctly.hashCode()
value while it's used as the keyHashMap
should be immutable. This would automatically ensure that 2. is always held true.I have two kinds of objects in my application where every object of one kind has exactly one corresponding object of the other kind.
This really sounds like a has-a relationship and thus could be implemented using a simple attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With