0

If I add an element to a hash map:

this.coloursHashMap1 = new HashMap<int[], int[]>();
int[] cols = new int[]{1,2,3};
int[] coord = new int[]{i,j,k};
this.coloursHashMap1.put(coord, cols);

And then try to access it, does anyone know why I can only get the data by calling getColourFromHashArr() and not getColourFromHashInts() - is the coord array created in the second method functionally different to one passed as a parameter into the first?

public int[] getColourFromHashArr(int[] coord){
    return this.coloursHashMap1.get(coord);
} //returns correct value

public int[] getColourFromHashInts(int i, int j, int k){
    int[] coord = new int[]{i,j,k};
    return this.coloursHashMap1.get(coord);
} //returns null

No matter what I do, I can't seem to get the value from another method, with only passing in the ints seperately. Is there something I'm missing?

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • See https://stackoverflow.com/questions/744735/java-array-hashcode-implementation – tgdavies Jan 19 '23 at 07:46
  • 2
    Side note: you should not use mutable objects like arrays as map keys, or at least you should be _very_ careful not to mutate them once they are used as a key. If you do, you'll mess up the map and won't be able to find those entries anymore (without looking at them all, that is). – Thomas Jan 19 '23 at 07:51

1 Answers1

0

Because two arrays are not equal, even if they contain the same elements. They are only consider equal, if they are the same reference (same memory location).

new int[]{1,2,3}.equals(new int[]{1,2,3}); // false
int[] a = new int[]{1,2,3};
a.equals(a); // true
int[] b = a;
a.equals(b); // true (same memory location)
knittl
  • 246,190
  • 53
  • 318
  • 364