Java的HashMap的使用int数组 [英] Java HashMap with Int Array
问题描述
您好
我用这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 thecontainsKey(Object key)
method says: "returnstrue
if and only if this map contains a mapping for a keyk
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
usesjava.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$c$c>和<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hash$c$c%28%29\"><$c$c>Object.hash$c$c$c$c>
- 这对于Java程序员要知道这些合同,以及如何使它们与/合作为系统的其余部分 是必不可少的
Object.equals
andObject.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屋!
- And don't forget that when you
- 不要忘记,当你