Nested Maps or combined keys in java

前端 未结 6 1667
一个人的身影
一个人的身影 2020-12-17 21:58

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

6条回答
  •  庸人自扰
    2020-12-17 22:50

    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);
    } 
    

提交回复
热议问题