我有一个以下程序,我有一个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,18}); myMap.put("DivisibleByFive",new int[]{5,20}); int[] array = new int[]{1,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,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环境的新手,因此很混乱.请帮我清楚一下这些概念.
解决方法
这是因为boolean x = new int [] {5,20} .equals(new int [] {5,20});返回false.一种解决方案是使用java.nio.IntWrapper,试试这个
map.put("a1",IntBuffer.wrap(new int[]{ 5,20 })); boolean equals = map.containsValue(IntBuffer.wrap(new int[]{ 5,20 }));