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
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 1 and 22 and keys 12 and 2. They'd map to the same value 122.
If you'll always use both keys, using a single Map will always be a little more efficient, and you can always define your own adapter to the map that will take two arguments:
public class MyCache {
private Map cache = new HashMap();
public Object getObject(Object key1, Object key2){
return cache.get(new MyKey(key1, key2));
}
public void putObject(Object key1, Object key2, Object value){
cache.put(new MyKey(key1, key2), value);
}
}
Remember to define equals() and hashCode() in your custom key class (add checks for nullity if needed).
public int hashCode() {
int result = 17;
result = 37 * result + keyA.hashCode();
result = 37 * result + keyB.hashCode();
return result;
}
public boolean equals(Object another) {
return another.keyA.equals(keyA) && another.keyB.equals(keyB);
}