有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有多个键的字典Java映射

我需要创建一个地图,有3列:2个键和1个值。因此,每个值将包含两个不同类类型的键,并且可以使用其中一个来获取。但我的问题是HashMap/Map只支持1个键和1个值。有没有办法创建类似于Map<Key1, Key2, Value>而不是Map<Key, Value>的东西?因此Value可以通过使用其Key1Key2来获取

我很抱歉,如果这是一个重复或错误的问题,但我在堆栈溢出上找不到类似的问题

附言:我不想创建两个映射:Map<Key1, Value>Map<Key2, Value>也不想创建嵌套映射我正在寻找一个多键表,就像上面那样


共 (5) 个答案

  1. # 1 楼答案

    要实现这一点,您可能需要编写一个类映射的自定义实现。我同意上面的@William Price,最简单的实现就是封装两个Map实例。使用Map接口时要小心,因为它们依赖equals()和hashCode()作为密钥标识,而您打算在合同中破坏密钥标识

  2. # 4 楼答案

    根据自己的要求编写课程:

    import java.util.HashMap;
    import java.util.Map;
    
    public class MMap<Key, OtherKey, Value> {
    
        private final Map<Key, Value> map = new HashMap<>();
    
        private final Map<OtherKey, Value> otherMap = new HashMap<>();
    
        public void put(Key key, OtherKey otherKey, Value value) {
            if (key != null) { // you can change this, if you want accept null.
                map.put(key, value);
            }
            if (otherKey != null) {
                otherMap.put(otherKey, value);
            }
        }
    
        public Value get(Key key, OtherKey otherKey) {
            if (map.containsKey(key) && otherMap.containsKey(otherKey)) {
                if (map.get(key).equals(otherMap.get(otherKey))) {
                    return map.get(key);
                } else {
                    throw new AssertionError("Collision. Implement your logic.");
                }
            } else if (map.containsKey(key)) {
                return map.get(key);
            } else if (otherMap.containsKey(otherKey)) {
                return otherMap.get(otherKey);
            } else {
                return null; // or some optional.
            }
        }
    
        public Value getByKey(Key key) {
            return get(key, null);
        }
    
        public Value getByOtherKey(OtherKey otherKey) {
            return get(null, otherKey);
        }
    }
    
  3. # 5 楼答案

    只需将值存储两次:

    Map<Object, Value> map = new HashMap<>();
    map.put(key1, someValue);
    map.put(key2, someValue);
    

    问题是,键是什么类型并不重要,所以使用一个允许两种键类型的泛型绑定-Object就可以了

    请注意,^{}方法的参数类型只是Object,所以从查找的角度来看,拥有单独的映射没有任何价值(键的类型只与^{}相关)