Search code examples
javaarraysdictionaryhashmapkey

Using string tuples as key for HashMap


I need Java equivalent for following 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:

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.

An inefficient way I can think of is concatenating elements from String[] into a single String.

Is there a better way?


Solution

  • 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.