I need a Map to make a cache in Java for same values that I have two String keys. My question it’s better to make nested Maps (one for each key) or make some type of custom key maked with the two Strings?
Access to data on cache will all time accessed with the two keys and I don’t need group it by any of that two keys.
Then if is better combine string key in only one what it’s better?
- Custom class with custom
getHashmethod. But then the problem is what hash function implement? -
Simply concatenate two strings together. For example:
cache.put(key1+key2, value)
You can either make nested maps or use a custom class defining
hashCode().It’s usually not a good idea to concatenate the keys, you can end up with collisions, as in the case with keys
1and22and keys12and2. They’d map to the same value122.If you’ll always use both keys, using a single
Mapwill always be a little more efficient, and you can always define your own adapter to the map that will take two arguments:Remember to define
equals()andhashCode()in your custom key class (add checks for nullity if needed).