I have several Sets that store the objects of the same class, but I want to specify a different identity function for each of them (i.e. say, in one set A==B if A.x==B.x, while in another A==B if A.y==B.y).
Currently I use TreeSets with different Comparators defined for each. I am wondering how the same thing can be done if I want to switch to HashSets. Java does not allow passing a separate hash function in the same way it allows Comparators for Sorted/Tree-based Collections. The only way that I can think of doing it would involve creating a different wrapper class and implementing the hashCode() method in each for the elements of each HashSet. Is there a better way of doing this?
How about creating separate subclasses for each set. The only difference for each subclass would be the overridden hash function that meets your criteria.
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