java中的嵌套映射或组合键 [英] Nested Maps or combined keys in java

查看:17
本文介绍了java中的嵌套映射或组合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 Map 来在 Java 中为我有两个 String 键的相同值创建缓存.我的问题是最好制作嵌套地图(每个键一个)或使用两个字符串制作某种类型的自定义键?

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?

  • 具有自定义 getHash 方法的自定义类.但问题是哈希函数实现了什么?
  • 简单地将两个字符串连接在一起.例如:

  • Custom class with custom getHash method. But then the problem is what hash function implement?
  • Simply concatenate two strings together. For example:

cache.put(key1+key2, value)

cache.put(key1+key2, value)

推荐答案

您可以制作嵌套地图或使用自定义类定义 hashCode().

You can either make nested maps or use a custom class defining hashCode().

连接键通常不是一个好主意,最终可能会发生冲突,例如键 122 以及键 122.它们会映射到相同的值 122.

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.

如果你总是使用两个键,使用单个 Map 总是会更高效一些,你总是可以定义你自己的适配器到带有两个参数的映射:

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<MyKey, Object> cache = new HashMap<MyKey, Object>();

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

记得在您的自定义键类中定义 equals()hashCode()(如果需要,添加无效检查).

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

这篇关于java中的嵌套映射或组合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆