Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EMF objects as keys

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.

like image 393
JesperE Avatar asked Jun 06 '11 12:06

JesperE


3 Answers

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.

like image 148
Sebastian Zarnekow Avatar answered Nov 01 '22 13:11

Sebastian Zarnekow


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.

like image 27
Eric Rosenberg Avatar answered Nov 01 '22 12:11

Eric Rosenberg


You can use EcoreUtil.equals(), if the algorithm behind the method suits your use case.

like image 1
André B. Avatar answered Nov 01 '22 13:11

André B.