Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an array be used as a HashMap key?

If a HashMap's key is a String[] array:

HashMap<String[], String> pathMap; 

Can you access the map by using a newly created String[] array, or does it have to be the same String[] object?

pathMap = new HashMap<>(new String[]{"korey", "docs"}, "/home/korey/docs"); String path = pathMap.get(new String[]{"korey", "docs"}); 
like image 876
Korey Hinton Avatar asked May 30 '13 14:05

Korey Hinton


People also ask

Can HashMap have ArrayList as key?

Yes you can have ArrayList s as a keys in a hash map, but it is a very bad idea since they are mutable. If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.

What can be used as HashMap key?

Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.

Can arrays be hashed?

hashCode(Object[]) method returns a hash code based on the contents of the specified array. If the array contains other arrays as elements, the hash code is based on their identities rather than their contents.

Can we convert array to map in Java?

To convert an array to a Map one should perform the following steps: Create a two-dimensional array of String items. Use toMap(Object[] array) method of ArrayUtils class to convert the given array into a Map.


2 Answers

It will have to be the same object. A HashMap compares keys using equals() and two arrays in Java are equal only if they are the same object.

If you want value equality, then write your own container class that wraps a String[] and provides the appropriate semantics for equals() and hashCode(). In this case, it would be best to make the container immutable, as changing the hash code for an object plays havoc with the hash-based container classes.

EDIT

As others have pointed out, List<String> has the semantics you seem to want for a container object. So you could do something like this:

HashMap<List<String>, String> pathMap;  pathMap.put(     // unmodifiable so key cannot change hash code     Collections.unmodifiableList(Arrays.asList("korey", "docs")),     "/home/korey/docs" );  // later: String dir = pathMap.get(Arrays.asList("korey", "docs")); 
like image 77
Ted Hopp Avatar answered Oct 17 '22 19:10

Ted Hopp


No, but you can use List<String> which will work as you expect!

like image 43
Tom Carchrae Avatar answered Oct 17 '22 19:10

Tom Carchrae