Defining mulched hash functions for the same object

I have several sets that store objects of the same class, but I want to specify a different identification function for each of them (for example, in one set A == B, if Ax == Bx, and in the other A == B if Ay == By).

I am currently using TreeSets with different Comparators defined for each. I am wondering how you can do the same if I want to switch to HashSets. Java does not allow you to pass a separate hash function in the same way that it allows you to compare comparators for sorted / tree-based collections. The only way I can do this is to create another wrapper class and implement the hashCode () method for each of the elements of each HashSet. Is there a better way to do this?

+3
source share
4 answers

You can try using THashSet in GNU Trove.This supports several hash strategies.

+2
source

. - -, .

+7

I do not know how best to do this. Your proposed solution (wrapper classes with different comparison logic) sounds very reasonable.

You mentioned the implementation of the method hashCode- do not forget to implement it as well equals.

+3
source

There is another option: you can copy the source for HashMapand replace the method hash(Object key)with something else (for example, a call Hasherthat works like Comparator TreeMap).

+2
source

Source: https://habr.com/ru/post/1726714/


All Articles