dhblah dhblah - 1 year ago 57
Java Question

Is it possible in java make something like Comparator but for implementing custom equals() and hashCode()

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. So I want to put all that objects in a set, but somehow make that objects to use custom provided hashCode() and equals(). Something like custom Comparator(), but for equals.

Answer Source

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


  1. Implement a wrapper class that holds an instance of the real class, and provides its own implementation of equals and hashCode.

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

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

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download