0

I have this class:

    public class MyClass{

        private static Map<int[], Terrain> allTerrain = new HashMap<int[], Terrain>();

        public static void main(String[] args){
            populate();
            int[] test = {0, 0};
            System.out.println(allTerrain.get(test));
        }

        private static void populate() {
            for (int i=0; i<10; i++) {
                int[] index = {i, i};
                allTerrain.put(index, new Terrain());
            }
            int[] test = {0, 0};
            System.out.println(allTerrain.get(test));
        }

    }

Inside the method the allTerrain.get() method returns the instance of the object, but when I use allTerrain.get() outside of the method, it returns null for all the entries. Everything runs on the main thread so concurrency is not a problem (I think). Any ideas on how to fix this?

spcan
  • 138
  • 5

3 Answers3

2

It's not retrieving the value from the allTerrain map both inside the scope and outside.

null
null

The problem, is that when you use an object for keys in a HashMap, it needs to implement hashcode and equals in a useful way. Arrays with the same values are not considered equal. Therefor they don't reference the same key

Boolean equal = new int[]{1, 2}.equals(new int[]{1, 2}) // is false
lyjackal
  • 3,984
  • 1
  • 12
  • 25
  • Well I don't know why, but when run inside the method it is returning things like: `com.terrain.Terrain@4f47d241` – spcan Oct 13 '17 at 00:50
1

Using an array as a key to your map as you are doing won't work unfortunately. Can a java array be used as a HashMap key

Perhaps try an Integer https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
0

Because arrays are equal only if they are the same object. One int[]{0,0} is not the same as another int[]{0,0}. You could define a type class for storing composite key or I'd say use lombok @value annotation, it creates sensible equals and hashCode method.

Ramandeep Nanda
  • 519
  • 3
  • 9