java - 使用 map 检查是否包含数组。但不起作用

标签 java arrays dictionary

我有一个关于 Java map 的问题。我用map来包含数组,我想检查map是否包含我想要的数组。但它不起作用。无论如何检查 map 是否包含我想要的数组?

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

最佳答案

这行不通:Map 基于哈希码和相等性检查;数组在计算它们的哈希码时不注意它们的元素。这就是为什么您尝试用作键的两个数组被认为是不同的。

您可以定义一个类ArrayKey,在构造函数中将数组放入其中,并定义使用数组元素的equalshashCode

关于java - 使用 map 检查是否包含数组。但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426422/

相关文章:

java - 非法状态异常 : migration from jboss 4 to jboss 5

java - 根据按另一个列表中的值排序的键对映射进行排序

java - 创建类型为 Field 的可观察列表

javascript - 过滤数组并匹配至少一个条件

java - 将Clojure的以vector为key的map转为java HashMap

java - 是否可以将 MapView 作为另一个 Activity 的元素包含在内?

java - Tomcat 和 logback.xml

c++ - 错误:The thread 0x4c0c has exited with code 0 (0x0). Exception thrown: read access violation. **this** was nullptr

python - Apache 光束 + Python : Writing JSON (or dictionaries) strings to output file

swift - 在 For 循环中添加到字典