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

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

问题描述

Hashcode()和equals()的概念是

lockquote
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);



$ / code $ / pre

上面的程序给出了相同的哈希码对于两个不同的对象。

有人可以用一个例子解释我,根据equals()不同的两个不同对象怎么能有相同的散列码。

解决方案


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


根据散列函数,2个不同的对象可以具有相同的散列码。但是,2个相同的对象在散列时必须产生相同的结果(除非某人在随机数中实现了散列函数,在这种情况下它是无用的)。例如,如果if我是散列整数,我的散列函数只是(n%10),然后是数字 17 和数字 27 会产生相同的结果。这并不意味着这些数字是相同的。


Hashcode() and equals() concept is

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

and other one is

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.

Can someone explain me with an example,how can two different objects which are unequal according to the equals() have same 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.

Depending on the hashing function, 2 different objects can have the same hash code. However, 2 objects wich 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)

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天全站免登陆