小编Sah*_*aha的帖子

两个具有相同哈希码的不等对象

Hashcode()和equals()的概念是

1)如果两个对象根据equal()相等,则在这两个对象中的每一个上调用hashcode方法应该产生相同的哈希码.

而另一个是

2)如果两个对象根据equal()不相等,则不需要在两个对象中的每一个上调用hashcode方法必须产生不同的值.

我尝试并理解了第一个,这是第一点的代码.

public class Test {
    public static void main(String[] args) {

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(1, 11);
        map.put(4, 11);
        System.out.println(map.hashCode());
        Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
        map1.put(1, 11);
        map1.put(4, 11);
        System.out.println(map1.hashCode());
        if (map.equals(map1)) {
            System.out.println("equal ");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的程序为两个不同的对象提供相同的哈希码.

有人可以用一个例子来解释我,根据equals()不同的两个不同对象如何具有相同的哈希码.

java equals hashmap hashcode

15
推荐指数
4
解决办法
3万
查看次数

标签 统计

equals ×1

hashcode ×1

hashmap ×1

java ×1