why '==' is returning false even after my

2019-03-04 00:00发布

I have a written a class like

public class HashCodeImpl{
    public int hashCode(){
        return 1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        HashCodeUtil h=  new HashCodeUtil();
        HashCodeUtil h1=  new HashCodeUtil();
        System.out.println(h.hashCode());
        System.out.println(h1.hashCode());
        System.out.println(h);
        System.out.println(h1);
        System.out.println(h==h1);
    }
}

OutPut:

1 
com.manu.test.HashCodeUtil@1  
com.manu.test.HashCodeUtil@1 false

My question is: when my hashCode method is returning same value then why System.out.println(h==h1); is coming false?

Please explain.

3条回答
时光不老,我们不散
2楼-- · 2019-03-04 00:43

As @ZouZou points out, hashCode equality does not equate to object equality. Having said that, you are not even comparing for object equality. Comparing two objects with == is a reference equality check, which you should almost never use, unless you really know what you're doing.

查看更多
迷人小祖宗
3楼-- · 2019-03-04 00:47

You're misunderstanding the purpose of the hashCode. As others have pointed out, == compares references and not hash codes. However, an overriding equals method, which compares values and not references, still wouldn't compare hash codes.

Think about it ... A hash code is an int, and therefore there are only 232 possible values for a hash code. But how many possible Strings are there? Many, many more than 232. (Since each char has 216 possible values, there are 248 possible Strings of length three, and the number just keeps growing the longer the Strings get.) Therefore, it is impossible to set up a scheme where two Strings are always equal if their hash codes are equal. The same is true of most other objects (although a class with a relatively small number of possible values could be set up with a unique hash code for each value).

The hashCode's purpose is to come up with a number that can be used for a hashMap or hashSet. We often try to come up with a function that will reduce that chance that unequal objects have unequal hash codes, in order to improve the efficiency of the map or set. But for most objects, of course, it's impossible to guarantee this.

查看更多
劳资没心,怎么记你
4楼-- · 2019-03-04 00:50

Because they are two different object references. == compare the references, not the hashCode results.

To get a desired result, you may override the equals method in your class and use h1.equals(h2) to see if they're equivalent. Here you may use the result of hashCode to ease the evaluation of the equality of the objects being compared (this doesn't mean that two objects with the same hash code are equals).

But note that even if the objects have the same hashCode and are equivalent by the definition of the equals method, they are different references that occupy a different place in the heap.

查看更多
登录 后发表回答