I have a requirement where multiple enums will need to find a value in the i.e. Map<Key,Value>
(combination of enums will return a unique value).
I think there are many options like having a wrapper Object say Key which will act as a Key. Also, we can use Guava Table if keys are limited to two (not sure).
Wanted to check for below approach where two enums will map to a unique computed value, need suggestions for understanding -
i) If this approach is fine?
ii) If Yes, is it scalable? i.e. can it be easily made generic to support 'n' enums
as in toKey(Enum ...enums)
Below is snippet for two enums -
static Integer toKey(Status s, SubStatus ss) {
return Integer.valueOf(s.ordinal() * SubStatus.values().length + ss.ordinal());
}
And
Status { NONE, PASS, WARN, REJECT }
SubStatus { NONE, SOFT_REJECT, HARD_REJECT }
Integer key1 = toKey(Status.REJECT, SubStatus.HARD_REJECT)
Integer key2 = toKey(Status.WARN, SubStatus.NONE)
then key1 != key2
Thanks!
You can try this code to generate a hash code which serves as a key:
It should be fairly robust against collisions due to the prime number and it is extendable to support n Enums.