Michael Vu Michael Vu - 2 months ago 17
Java Question

Can a hashmap in java take a int array as it's key?

For a Java problem I'm doing currently, I am trying to set the key of a hashmap as an

array, as the key are coordinates in a 2d array. The value it has is also an
array of values, but my code is returning null. Am I right in saying that an
array as a key in a hashmap won't work?


You could probably force this to work but the far better way would be for you to define a Coordinate class which would contain the coordinate data as fields:

class Coordinate
    // Perhaps make this an array if your system has high dimensionality.
    double x, y;

Then, if you provide overrides for equals and hashCode (many IDEs will generate proforma versions of these functions for you.) , you'll be able to use Coordinate instances as hash map keys.

My way scales well. Going forward, you'd start encapsulating the fields, defining constructors, and perhaps even methods for converting to different coordinate systems.