微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 关于Map.containsValue方法的混淆

我有一个以下程序,我有一个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 }));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐