使用 EMF 对象作为键

发布于 2024-11-14 05:33:32 字数 93 浏览 4 评论 0原文

是否可以让 EMF 对象实现 hashCodeequals ?我希望能够使用模型对象作为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一花一树开 2024-11-21 05:33:32

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.

熟人话多 2024-11-21 05:33:32

如果该方法背后的算法适合您的用例,您可以使用 EcoreUtil.equals()。

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

庆幸我还是我 2024-11-21 05:33:32

我绝不是 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 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.

神经暖 2024-11-21 05:33:32

或者,您可以为每个 EMF-*Impl 类实现(生成)equals / hashCode 方法。您必须在方法标题上方插入 @ generated not 注释。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文