Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any disadvantage to using arbitrary objects as Map keys in Java?

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?

like image 659
Hanno Fietz Avatar asked Mar 11 '09 15:03

Hanno Fietz


2 Answers

  1. The key needs to implement .equals() and .hashCode() correctly
  2. The key must not be changed in any way that changes it's .hashCode() value while it's used as the key
  3. Ideally any object used as a key in a HashMap should be immutable. This would automatically ensure that 2. is always held true.
  4. Objects that could otherwise be GCed might be kept around when they are used as key and/or value.
like image 189
Joachim Sauer Avatar answered Nov 09 '22 19:11

Joachim Sauer


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.

like image 21
Aaron Maenpaa Avatar answered Nov 09 '22 19:11

Aaron Maenpaa