我可以在 Scala 中创建一个使用不同 equals/hashCode/compare 实现的集合吗? [英] Can I create a collection in Scala that uses different equals/hashCode/compare implementations?

查看:31
本文介绍了我可以在 Scala 中创建一个使用不同 equals/hashCode/compare 实现的集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找创建身份集的简单方法.我只是希望能够在遍历图形时跟踪我是否看到"了特定对象.

I'm looking for as simple way to create an identity set. I just want to be able to keep track of whether or not I've "seen" a particular object while traversing a graph.

我不能使用常规 Set,因为 Set 使用=="(Scala 中的 equals 方法)来比较元素.我想要的是一个使用eq"的 Set.

I can't use a regular Set because Set uses "==" (the equals method in Scala) to compare elements. What I want is a Set that uses "eq."

有什么方法可以在 Scala 中创建一个 Set ,它使用一些应用程序指定的方法来测试相等性而不是在 set 元素上调用 equals 吗?我寻找了某种可以覆盖但没有找到的wrapEquals"方法.

Is there any way to create a Set in Scala that uses some application-specified method for testing equality rather than calling equals on the set elements? I looked for some kind of "wrapEquals" method that I could override but did not find it.

我知道我可以使用 Java 的 IdentityHashMap,但我正在寻找更通用的东西.

I know that I could use Java's IdentityHashMap, but I'm looking for something more general-purpose.

我的另一个想法是将每个 set 元素包装在另一个对象中,该对象在 eq 方面实现了 equals,但是为了获得新的 equals 实现而生成大量新对象是一种浪费.

Another idea I had was to just wrap each set element in another object that implements equals in terms of eq, but it's wasteful to generate tons of new objects just to get a new equals implementation.

谢谢!

推荐答案

这是一个类似的问题.在这种情况下,可接受的答案是使用 TreeSet 并提供自定义 Comparator.

This is a similar question. The accepted answer in that case was to use a TreeSet and provide a custom Comparator.

这篇关于我可以在 Scala 中创建一个使用不同 equals/hashCode/compare 实现的集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆