地图中两个字符串的键?

时间:2011-02-17 09:20:35

标签: java map tuples apache-commons

我需要创建一个包含两个字符串键的地图。

例如,让我们说

key = Name & Target
value = Permission(boolean)

我是否需要创建一个特殊对象,或者在Java / Google Collections或Commons Collections或Commons Lang中是否有任何构建元组?

4 个答案:

答案 0 :(得分:11)

Apache Commons Collections有MultiKey

map.put(new MultiKey(key1, key2), value);

MultiKeyMap

multiKeyMap.put(key1, key2, value);

答案 1 :(得分:5)

为什么不从这两个字符串创建List并将其用作Map中的密钥。这样可以使代码更具可读性。

答案 2 :(得分:3)

你可以将字符串拼凑在一起,但我个人的偏好是创建一个小值对象:

public class NameTarget {
    private final String name;
    private final String target;

    public NameTarget(String name, String target){
        this.name = name;
        this.target = target;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((target == null) ? 0 : target.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        NameTarget other = (NameTarget) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (target == null) {
            if (other.target != null)
                return false;
        } else if (!target.equals(other.target))
            return false;
        return true;
    }

    // add getters here
}

在eclipse中生成do需要大约30秒,从长远来看,它可以使代码更安全,更清晰。

你可以和我过去创建一个Pair样式的turple但是我开始更喜欢这种事情的命名不可变值类型。

答案 3 :(得分:1)

这是你要找的吗?

String name = ...
String target = ...
String key = name + "_" + target;

map.put(key, value)

或者,您可以创建一个包含两个字符串的对象,并覆盖hashCodeequals例程,以便以比简单字符串连接更好的方式进行区分。