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.
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.
Now when the javadocs talk about comparisons being "consistent with equals", then "equals" in this context always refers to the equals(Object) method of the object to be compared, may that object implement Comparable itself or just be compared to another object with a Comparator .
The equals Method obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.
Yes. You can also override the equals() method and play with it.
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 ...)
Alternatives:
Implement a wrapper class that holds an instance of the real class, and provides its own implementation of equals
and hashCode
.
Implement your own hashtable-based classes which can use a "hashable" object to provide equals and hashcode functionality.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With