简体   繁体   English

哈希码,等于Java中的合同

[英]Hashcode , equals contract in java

public class VO {

    public int hashcode()
    {
        return 0;
    }
    public boolean equals(Object obj)
    {
        return true;
    }

    public static void main(String args[])
    {
        VO vo1 = new VO();
        VO vo2 = new VO();

        Map<VO,Integer> map = new HashMap<VO, Integer>();

        map.put(vo1, 1);
        map.put(vo2, 1);

        System.out.println(map.size());
    }
}

I am getting the output is :2 我得到的输出是:2

But as per my knowledge the output is 1. 但是据我所知输出是1。

When i am placing an element in map it will check the hashcode for the key,if that hashcode is same then it will go to check equals.If both the methods returns same it will override the previous value. 当我在地图上放置一个元素时,它将检查密钥的哈希码,如果该哈希码相同,则它将去检查是否等于。如果两种方法返回的结果相同,它将覆盖先前的值。

In my case both the methods are(hashcode and equals) returns 0 and true.So finally there must be one element in the map.But here i am getting size as 2. 在我的情况下,这两个方法are(hashcode and equals)返回0和true。所以最后在映射中必须有一个元素。但是在这里我得到的大小是2。

What might be the reason.Thanks in dvance... 可能是什么原因。谢谢...

You are not overriding Object.hashCode , you're implementing your own hashcode() method (mind the capitalized C). 您没有覆盖Object.hashCode ,而是实现了自己的hashcode()方法(请注意大写的C)。

A good practice is to always use @Override annotations when overriding. 一个好的做法是在@Override时始终使用@Override批注。 See: When do you use Java's @Override annotation and why? 请参阅: 什么时候使用Java的@Override注释,为什么?

hashcode() ( with small "c" ) was just acting as a normal method, and instead Object class method hashCode() was called. hashcode()带有小“ c” )仅用作常规方法,而是调用对象类方法hashCode()

public class VO {

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public boolean equals(Object obj) {
        return true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM