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 ...)
Alternatives:
Implement a wrapper class that holds an instance of the real class, and provides its own implementation of
equals
andhashCode
.Implement your own hashtable-based classes which can use a "hashable" object to provide equals and hashcode functionality.
Bite the bullet and implement
equals
andhashCode
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.
Read full article from collections - Is it possible in java make something like Comparator but for implementing custom equals() and hashCode() - Stack Overflow
No comments:
Post a Comment