law
law

Reputation: 47

Use map to check whether contains the array. But does not work

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");
   }
 }
}

Upvotes: 2

Views: 2589

Answers (3)

Jon Lin
Jon Lin

Reputation: 143946

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.

Upvotes: 1

Gabriel Belingueres
Gabriel Belingueres

Reputation: 2985

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.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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.

Upvotes: 4

Related Questions