具有自定义相等标准的Java HashSet? [英] Java HashSet with a custom equality criteria?

查看:146
本文介绍了具有自定义相等标准的Java HashSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似于Java TreeSet在实例化时接收自定义比较器的能力,所以我不需要使用对象的默认相等(和哈希码)标准。

I was looking for something akin to the Java TreeSet's ability to receive a custom comparator at instantiation time, so I needed not to use the object's default equality (and hash code) criteria.

我能想到的最接近的是将我的对象包装在一个私有的自定义类中,但这看起来很糟糕:(这在编程时最终会成为一种反复出现的主题,所以我想知道是否已有可用的东西供我们使用。也许在公共图书馆?

The closest I could come up with was to wrap my objects in a private custom class, but that seems hacky :( This ends up being a kind of recurring theme when programming, so I was wondering if there's something already available for us to use. Maybe in the commons libraries?

谢谢

推荐答案

<不,你已经找到了你应该使用的解决方案。

Nope, you've found exactly the solution you're supposed to use.

即使对于 TreeSet ,它是不赞成使用的比较标准与兼容等于

Even for TreeSet, it's frowned upon to use comparison criteria that aren't compatible with equals:


请注意由排序集维护的排序(无论是否是明确的如果有序集合要正确实现Set接口,则必须与equals一致。

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface.

(我不知道Apache Commons,但是Guava 具体 拒绝了这类事情的请求。)

(I don't know about Apache Commons, but Guava specifically rejected requests for this sort of thing.)

这篇关于具有自定义相等标准的Java HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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