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" });
It will have to be the same object. A
HashMap
compares keys usingequals()
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 forequals()
andhashCode()
. 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:Ted Hopp is right it will have to be same object
for information see this example
When you run above it will print "docs".
Arrays in Java use
Object
'shashCode()
and don't override it (the same thing withequals()
andtoString()
). So no, youcannotshouldn't use arrays as a hashmap key.No, but you can use
List<String>
which will work as you expect!You cannot use a plain Java
Array
as a key in aHashMap
. (Well you can, but it won't work as expected.)But you could write a wrapper class that has a reference to the Array and that also overrides
hashCode()
andequals()
.In most cases, where the Strings inside your array are not pathological and do not include commas followed by a space, you can use
Arrays.toString()
as a unique key. i.e. yourMap
would be aMap<String, T>
. And the get/put for an arraymyKeys[]
would beObviously you could put in some wrapper code if desired.
A nice side effect is that your key is now immutable. Of course, of you change your array myKeys and then try a
get()
, you won't find it.Hashing of Strings is highly optimized. So my guess is that this solution, though it feels a bit slow and kludgy, will be both faster and more memory efficient (less object allocations) than @Ted Hopp solution using an immutable List. Just think about whether
Arrays.toString()
is unique for your keys. If not, or if there is any doubt, (e.g. the String[] comes from user input) use the List.