使用 EMF 对象作为键
是否可以让 EMF 对象实现 hashCode
和 equals
?我希望能够使用模型对象作为 HashMap 中的键。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
EObject 的 javadoc 对此很清楚。 EObject 不能专门化
hashCode
或equals
。但是,只要您了解Object#equals(..)
和#hashCode
的标识语义,就可以在映射中使用它们。EObject's javadoc is clear about that. An EObject may not specialize
hashCode
orequals
. However, you can use them in maps as long as you are aware of the identity semantics ofObject#equals(..)
and#hashCode
.如果该方法背后的算法适合您的用例,您可以使用 EcoreUtil.equals()。
You can use
EcoreUtil.equals()
, if the algorithm behind the method suits your use case.我绝不是 EMF 专家,但您可以为 EObject 创建一个包装器对象,并根据来自您感兴趣的 EObject,然后使用该包装器作为键。这将迫使您在搜索地图时始终实例化包装器对象,但根据使用模式可能不会太令人讨厌。
请注意,使用可变对象作为映射中的键是很棘手的。如果对象在用作密钥后发生变异,导致哈希码发生变化,那么以后可能很难再次找到该密钥。
I'm by no means an EMF expert but you could create a wrapper object for the EObject and implement the
equals
andhashCode
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.
或者,您可以为每个
EMF-*Impl
类实现(生成)equals
/hashCode
方法。您必须在方法标题上方插入@ generated not
注释。Or you can implement (generate)
equals
/hashCode
methods for eachEMF-*Impl
class. You have to insert a@generated not
comment above the method header.