我有一个下面的程序,其中有一个 HashMap 。 HashMap 的键是简单的整数,值是整数数组。程序如下:
Map<String , int []> myMap = new HashMap<String , int []>();
myMap.put("EvenNumbers", new int[]{2,4,6,8,10,12,14,16,18,20});
myMap.put("OddNumbers", new int[]{1,3,5,7,9,11,13,15,17,19});
myMap.put("DivisibleByThree", new int[]{3,6,9,12,15,18});
myMap.put("DivisibleByFive", new int[]{5,10,15,20});
int[] array = new int[]{1,3,5,7,9,11,13,15,17,19};
System.out.println(myMap.containsKey("EvenNumbers"));
System.out.println(myMap.containsKey("OddNumbers"));
//The following two lines produce a false output. Why ?
System.out.println(myMap.containsValue(new int[]{5,20,15,20} ));
System.out.println(myMap.containsValue(array));
而下面的代码产生一个真值
HashMap newmap = new HashMap();
// populate hash map
newmap.put(1, "tutorials");
newmap.put(2, "point");
newmap.put(3, "is best");
// check existence of value 'point'
System.out.println("Check if value 'point' exists: " +
newmap.containsValue("point"));
为什么会这样?我哪里出错了?我缺少的概念是什么?我觉得我在这两种情况下都在做同样的事情。我是 java 环境的新手,因此很困惑。请帮我理清概念。
最佳答案
看看equals vs Arrays.equals in Java
Map 使用等于来确定一个值是否存在于 Map 中,但它意味着不同的事情:
- 当您在第一种情况下比较 2 个数组时,您是在检查这是否是同一个数组,意思是内存中的位置,而不是数组的内容。
- 在第二种情况下,String.equals 实际上检查这是否是同一个字符串。
关于java - 对 Map.containsValue 方法的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622914/