Java - Using String Tuples as a Key for HashMap

I need java equivalent for next python

In [1]: d = {} In [2]: k = ("x","2") In [3]: d[k] = 1 In [4]: print d[("x","y")] 1 

Python has tuples that you can use. I tried unsuccessfully to follow in 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"})); 

He outputs

 1 null 

This means that a reference to String [] receives a hash instead of a value.

An inefficient way that I can think of is to concatenate the elements from String [] into one string.
Is there a better way?

Thanks in advance!

+6
source share
3 answers

Arrays in Java do not provide the hashCode() and equals(Object) methods, so they are not suitable as map keys. Instead, you can use Arrays.asList(string1, string1, etc) , which will give you an immutable List , which all methods are needed for the Map key.

+1
source

HashMaps uses Object.hashCode() to create a hash. By default, it uses a hash of an object that is unique to each instance, but does not examine the contents.

You want to create a tuple that overrides hashCode() and, in addition, remains unchanged after creation:

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

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

+6
source

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

+1
source

Source: https://habr.com/ru/post/957475/


All Articles