具有相同哈希码的两个不相等对象 [英] two unequal objects with same hashcode

查看:52
本文介绍了具有相同哈希码的两个不相等对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hashcode()和equals()的概念是

Hashcode() and equals() concept is

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

1) If two Objects are equal according to equal(), then calling the hashcode method on each of those two objects should produce same hashcode.

另一个是

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

2) It is not required that if two objects are unequal according to the equal(), then calling the hashcode method on each of the two objects must produce distinct values.

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

I tried and understood first one and this is the code for first point.

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 ");
        }
    }
}

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

the above program gives same hashcode for two different objects.

谁能用一个例子解释一下,根据 equals() 不相等的两个不同对象如何具有相同的哈希码.

Can someone explain me with an example,how can two different objects which are unequal according to the equals() have same hashcode.

推荐答案

2) 不要求如果两个对象根据equal()是不相等,那么对两个对象中的每一个调用hashcode方法都必须产生不同的价值观.

2) It is not required that if two objects are unequal according to the equal(), then calling the hashcode method on each of the two objects must produce distinct values.

根据散列函数,2 个不同的对象可以具有相同的散列码.但是,相同的 2 个对象在散列时必须产生相同的结果(除非有人使用随机数实现散列函数,在这种情况下它是无用的)

Depending on the hashing function, 2 different objects can have the same hash code. However, 2 objects which are the same must produce the same result when hashed (unless someone implemented a hashing function with random numbers in which case it's useless)

例如,如果我正在对整数进行哈希处理,而我的哈希函数只是 (n % 10) 那么数字 17 和数字 27 将产生相同的结果.这并不意味着这些数字是相同的.

For example, if I am hashing integers and my hashing function is simply (n % 10) then the number 17 and the number 27 will produce the same result. This does not mean that those numbers are the same.

这篇关于具有相同哈希码的两个不相等对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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