本文介绍了2个HashMap之间的平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 所有, 在我的类的equals()方法中,我使用私有实例HashMap变量来比较相等性。然而,在比较它们的HashMap变量时,2个不同的对象仍然显示相同。进一步的研究让我看到了链接:链接到这里。但是,它只是说HashMap1.equals(HashMap2)不起作用的原因是因为在没有编写自定义代码的情况下,显然Java的数组无法测试相等性。 我不明白这个原因。任何人都可以请我指出一个详尽的理由吗?解决方案 等于方法在Java数组类型上相当于 == ,因为Java数组类不会覆盖 Object.equals 。 如果你想比较按值的数组,你需要使用适当的 java.util.Arrays.equals(... )方法,或自己实现。 如果 HashHap 使用数组作为键或值,这会使 HashMap.equals 表现得很奇怪(从你的角度来看)。这就是链接文章所说的。但是,如果将数组作为(或在)键或值类中使用,则数组语义 only 会影响 HashMap 如果你不这样做,那么 equals 应该按预期工作。 c $ c> Map 类有点涉及,但它们基本归结为取两个入口集,比较它们的大小,然后执行 s1.containsAll(s2)。当然,这很贵,但它应该适用于所有正确实现 Map 类的 Map 接口。) All,In the equals() method of my class, I am using a private instance HashMap variable to compare for the equality. However, 2 different objects still show being equal when comparing their HashMap variables. Further research brought me to the link : Link Here . However, it just says that the reason for HashMap1.equals(HashMap2) not working is because " apparantly Java's arrays cannot be tested for equality without writing a customized code." I did not understand this reason. Can anyone please guide me to a elaborate reason? 解决方案 The equals method on a Java array type is equivalent to ==, because Java array "classes" do not override Object.equals.If you want to compare arrays "by value" you need to either use the appropriate java.util.Arrays.equals(...) method, or implement it yourself.If your HashHap uses arrays as keys or values, this would make HashMap.equals behave strangely (from your perspective). That is what the linked article is saying. However, array semantic only affect HashMap equality if you use arrays as (or in) the key or value classes. If you don't, then equals should just work as expected.(The javadocs for equality on Map classes are a bit involved, but they basically boil down to taking the two entry sets, comparing their sizes, and then doing s1.containsAll(s2). Of course, this is expensive, but it should work for all of the Map classes that correctly implement the Map interface.) 这篇关于2个HashMap之间的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 09:33