Is it possible to have EMF objects implement hashCode
and equals
? I would like to be able to use a model object as a key in a HashMap
.
EObject's javadoc is clear about that. An EObject may not specialize hashCode
or equals
. However, you can use them in maps as long as you are aware of the identity semantics of Object#equals(..)
and #hashCode
.
I'm by no means an EMF expert but you could create a wrapper object for the EObject and implement the equals
and hashCode
methods in the wrapper in terms of the attributes from the EObject you are interested in and then use that wrapper as the key. That would force you always to instantiate a wrapper object when searching the map, but depending on the usage pattern that may not be too hateful.
Be aware that using mutable objects as keys in a map is tricky. If the object is mutated after being used as a key in such a way that the hash code changes then it may be difficult to find the key again later.
You can use EcoreUtil.equals()
, if the algorithm behind the method suits your use case.
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