Skip to content
Advertisement

Can an array be used as a HashMap key?

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

JavaScript

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

JavaScript

Advertisement

Answer

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:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement