2

I have a question about Java maps. I use map to contain array, and I want to check whether the map contains the array I want. But it does not work. Is there anyway to check whether the map contains the the array I want?

import java.util.*;

 public class testContainKey{
 static Map<int[],Integer> map = new HashMap<int[], Integer>(); 
  public static void main(String args[]){
   int[] initial={1,2,3,4,5,6,7,8,9};
   int[] goal = {1,2,3,4,5,6,7,8,9};
   map.put(goal,0);
   if(map.containsKey(array)){
    System.out.println("OK");
  }
   else{
     System.out.println("Not works");
   }
 }
}
Kevin
  • 53,822
  • 15
  • 101
  • 132
law
  • 47
  • 1
  • 1
  • 4
  • possible duplicate of [Using a byte array as HashMap key (Java)](http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java) – Harry Joy Dec 08 '11 at 05:16

3 Answers3

4

This is not going to work: Map is based on hash code and equality checks; arrays do not pay attention to their elements when calculating their hash code. That's why the two arrays that you tried to use as keys are considered different.

You can define a class ArrayKey, put an array into it in a constructor, and define equals and hashCode that use array elements.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You are using as a key of the map an array, which is pretty much hard to control, because AFAIK you can not modify the equals() and hashCode() of it.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Gabriel Belingueres
  • 2,945
  • 1
  • 24
  • 32
1

When you call Map.containsKey(), it is using the array's .equals(), which compares the 2 objects. Since initial and goal are 2 different arrays, initial.equals(goal) will be false, always, even though the contents of the array are the same.

Something you can do is extend Map and override Map.containsKey() to check for int[], and compare each of the elements to determine equality.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Jon Lin
  • 142,182
  • 29
  • 220
  • 220