java - 使用字符串元组作为 HashMap 的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19805077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:20:09  来源:igfitidea点击:

java - Using string tuples as key for HashMap

javahashmap

提问by Nullpoet

I need java equivalent for following python

我需要 Java 等价物来跟随 python

In [1]: d = {}

In [2]: k = ("x","2")

In [3]: d[k] = 1

In [4]: print d[("x","y")]
1

Python has tuples which are hashable.
I tried following in Java unsuccessfully

Python 具有可散列的元组。
我尝试在 Java 中跟随失败

Map<String[], Integer> d = new HashMap<String[], Integer >();
String[] k = new String[]{"x", "y"};
d.put(k, 1);
System.out.println(d.get(k));
System.out.println(d.get(new String[]{"x", "y"}));

It outputs

它输出

1
null

This means reference to String[] is getting hashed instead of the value.

这意味着对 String[] 的引用被散列而不是值。

An inefficient way I can think of is concatenating elements from String[] into a single string.
Is there a better way?

我能想到的一种低效方法是将 String[] 中的元素连接成一个字符串。
有没有更好的办法?

Thanks in advance!

提前致谢!

采纳答案by Mureinik

Arrays in Java don't provide hashCode()and equals(Object)methods, so they aren't appropriate as map keys. What you could use instead is Arrays.asList(string1, string1, etc)which would give you an immutable List, which all the methods needed for a Map's key.

Java 中的数组不提供hashCode()equals(Object)方法,因此它们不适合作为映射键。你可以使用的是Arrays.asList(string1, string1, etc)它会给你一个不可变的List,它是 aMap键所需的所有方法。

回答by Johannes H.

HashMaps use Object.hashCode()to create the hash. This, by default, uses a hash of the object that is unique for each instance - but doesn't look into any contents.

HashMaps 用于Object.hashCode()创建哈希。默认情况下,这使用每个实例唯一的对象哈希 - 但不会查看任何内容。

You migth want to create a tuple that overrides hashCode()and, in addition to that, is immutable once created:

您可能想要创建一个覆盖的元组,hashCode()除此之外,一旦创建即不可变:

public class Tuple<T> {
    private final T[] contents;

    public Tuple (T[] contents) {
        if (contents.length != 2)
            throw new IllegalArgumentException();
        this.contents = contents;
    }

    public T[] getContents () {
        return this.contents.clone();
    }

    @Override
    public int hashCode () {
        return Arrays.deepHashCode(this.contents);
    }

    @Override
    public boolean equals (Object other) {
        return Arrays.deepEquals(this.contents, other.getContents());
    }

    @Override
    public String toString () {
        return Arrays.deepToString(this.contents);
    }
}

[Edit]: Note that, if mutable objects are used instead of strings, the getter must perform a deep copy, not just a simple clone()to ensure immutability.

[编辑]:请注意,如果使用可变对象而不是字符串,则 getter 必须执行深度复制,而不仅仅是clone()确保不变性的简单操作。

回答by user949300

You could use Arrays.toString(myArray) as your key.

您可以使用 Arrays.toString(myArray) 作为您的键。