是否可以在 java 中制作类似 Comparator 的东西,但用于实现自定义的 equals() 和 hashCode() [英] Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()

查看:17
本文介绍了是否可以在 java 中制作类似 Comparator 的东西,但用于实现自定义的 equals() 和 hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想将它与另一个对象数组连接起来,除了具有相同 ID 的对象.该对象在系统中的许多地方使用,并且没有实现哈希码或等号.所以我不想实现 hashCode()equals(),因为我害怕在使用这些对象的系统中的某个地方破坏某些东西,我不不知道.

I have an array of objects and I want to concatenate it with another array of objects, except that objects that have same id's. That objects are used in many places in the system and don't have hash code or equals implemented. So I don't want to implement hashCode() and equals(), cause I'm afraid to break something somewhere in the system where that objects are used and I don't know about that.

我想将所有这些对象放在一个集合中,但以某种方式使这些对象使用自定义的 hashCode()equals().类似于自定义 Comparator,但用于 equals.

I want to put all that objects in a set, but somehow make the objects use custom hashCode() and equals(). Something like custom Comparator, but for equals.

推荐答案

是的,可以做这样的事情.(而且人们已经这样做了.)但是它不允许您将对象放入 HashMapHashSet 等中.这是因为标准集合类期望关键对象本身提供 equalshashCode 方法.(这就是他们设计的工作方式......)

Yes it is possible to do such a thing. (And people have done it.) But it won't allow you to put your objects into a HashMap, HashSet, etc. That is because the standard collection classes expect the key objects themselves to provide the equals and hashCode methods. (That is the way they are designed to work ...)

替代方案:

  1. 实现一个包含真实类实例的包装类,并提供自己的 equalshashCode 实现.

实现您自己的基于哈希表的类,该类可以使用哈希"对象以提供 equals 和 hashcode 功能.

Implement your own hashtable-based classes which can use a "hashable" object to provide equals and hashcode functionality.

硬着头皮在相关类上实现 equalshashCode 覆盖.

Bite the bullet and implement equals and hashCode overrides on the relevant classes.

事实上,第三个选项可能是最好的,因为您的代码库很可能需要使用一致的概念,即这些对象相等意味着什么.还有其他一些事情表明您的代码需要大修.例如,它当前使用对象数组而不是 Set 实现来表示显然应该是一个集合的内容.

In fact, the 3rd option is probably the best, because your codebase most likely needs to to be using a consistent notion of what it means for these objects to be equal. There are other things that suggest that your code needs an overhaul. For instance, the fact that it is currently using an array of objects instead of a Set implementation to represent what is apparently supposed to be a set.

另一方面,当前实现可能存在/存在一些真实(或想象)的性能原因;例如减少内存使用.在这种情况下,您可能应该编写一堆辅助方法来执行诸如连接表示为数组的 2 个集合之类的操作.

On the other hand, maybe there was/is some real (or imagined) performance reason for the current implementation; e.g. reduction of memory usage. In that case, you should probably write a bunch of helper methods for doing operations like concatenating 2 sets represented as arrays.

这篇关于是否可以在 java 中制作类似 Comparator 的东西,但用于实现自定义的 equals() 和 hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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