Java的HashMap的使用int数组 [英] Java HashMap with Int Array

查看:429
本文介绍了Java的HashMap的使用int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好
我用这code检查数组中的HashMap present。

Hello I am using this code to check that array is present in the HashMap.

public class Test {
    public static void main(String[]arg)
    {
     HashMap<int[],String> map= new HashMap<int[],String>();
     map.put(new int[]{1,2}, "sun");
     System.out.println(map.containsKey((new int[]{1,2})));
    }
}

但这种打印假。
我怎么能检查数组中的HashMap的present。
先谢谢了。

But this prints False. How can I check that array is present in the HashMap. Thanks in advance.

推荐答案

问题是因为两个 INT [] 是不相等的。

The problem is because the two int[] aren't equal.

System.out.println(
    (new int[] { 1, 2 }).equals(new int[] { 1, 2 })
); // prints "false"

地图和其他Java集合框架类定义的接口在而言等于。从 地图API

Map and other Java Collections Framework classes defines its interface in terms of equals. From Map API:

在集合框架接口的许多方法中的等于方法的术语的定义。例如,对于中的containsKey(对象键)法的规范说:返回真正当且仅当此地图包含一键 K ,使得(键== NULL满足K ==空?key.equals(K))的映射

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))."

请注意,它们不必是相同的对象;他们只需要为等于。在Java数组从对象,其默认实现的等于仅在对象标识返回true延伸;因此为什么它打印假上面段

Note that they don't have to be the same object; they just have to be equals. Arrays in Java extends from Object, whose default implementation of equals returns true only on object identity; hence why it prints false in above snippet.

您可以在众多方法之一解决您的问题:

You can solve your problem in one of many ways:


  • 定义数组的等于使用的 java.util.Arrays中的 等于/ deepEquals 方法。

    • 不要忘记,当你 @覆盖等于(对象),还必须 @覆盖哈希code

    • Define your own wrapper class for arrays whose equals uses java.util.Arrays equals/deepEquals method.
      • And don't forget that when you @Override equals(Object), you must also @Override hashCode
      • Overriding equals and hashCode in Java
      • How to ensure hashCode() is consistent with equals()?
      • Understanding the workings of equals and hashCode in a HashMap

      • <$c$c>Object.equals和<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hash$c$c%28%29\"><$c$c>Object.hash$c$c

        • 这对于Java程序员要知道这些合同,以及如何使它们与/合作为系统的其余部分
        • 是必不可少的
        • Object.equals and Object.hashCode
          • It's essential for a Java programmer to be aware of these contracts and how to make them work with/for the rest of the system

          这篇关于Java的HashMap的使用int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆