Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining muliple hash functions for the same object

Tags:

java

hash

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?

like image 808
MAK Avatar asked May 15 '26 19:05

MAK


1 Answers

How about creating separate subclasses for each set. The only difference for each subclass would be the overridden hash function that meets your criteria.

like image 56
Poindexter Avatar answered May 18 '26 09:05

Poindexter