Michael Vu Michael Vu - 1 month ago 11
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

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

Answer

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.

Comments