I have a class and different equivalence rules on it (different implementation of equals and hashCode). The data is generated in one process first, where one equivalence rule is applied, and then fed to the second process, where the other equivalence rule is applied. Particularly, I am doing a lot of map operations and equals and hashCode are called implicitly by the standard library (which I do not have control on). What do you think is the best way to achieve this? I have two solutions now:
- Define two subclasses with different
equalsandhashCode. After process 1, do the conversion by initiating objects of the other subclass. - Introduce mutable states in the class to indicate which equivalence rule to apply.
So which one do you think is better or is there any other good solutions?
Finally I find that writing my own customized
Mapis the way to go (at least in my problem). After I dig into the scala standard library for a while, I figure out that it is extremely easy. No matter whether mutable or not, the element equality and hashCode methods inHashMapare inherited fromHashTableandHashTable.Utilsand are protected, meaning any subclass can override it easily. So the following is what I end up with:I did a simple test and it worked well.