繁体   English   中英

具有多个键的Java Map

[英]Java Map with multiple keys

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

如果是重复的问题或不好的问题,我深表歉意,但是我在Stack Overflow上找不到类似的问题。

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

您可能必须编写类似地图的类的自定义实现才能实现此目的。 我同意上面的@William Price,最简单的实现是简单地封装两个Map实例。 使用Map接口时要小心,因为它们依赖equals()和hashCode()来确定密钥身份,您打算在合同中打破这些身份。

自己编写符合您要求的课程:

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

只需将值存储两次:

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

问题是,它并不重要,关键是什么类型的,所以用一个通用的绑定,允许两种密钥类型- Object是罚款。

请注意, Map#get()方法的参数类型始终只是Object ,因此从查找角度看,拥有单独的映射没有任何价值(键的类型仅与put()有关)。

看一看可以在您的上下文中使用的番石榴的Table集合

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html

 Table<String,String,String> ==> Map<String,Map<String,String>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM