JesperE
JesperE

Reputation: 64414

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.

Upvotes: 7

Views: 1303

Answers (4)

Eric Rosenberg
Eric Rosenberg

Reputation: 1533

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.

Upvotes: 2

Sebastian Zarnekow
Sebastian Zarnekow

Reputation: 6729

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.

Upvotes: 10

daqua
daqua

Reputation: 1

Or you can implement (generate) equals / hashCode methods for each EMF-*Impl class. You have to insert a @generated not comment above the method header.

Upvotes: -1

André B.
André B.

Reputation: 689

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

Upvotes: 2

Related Questions