简体   繁体   中英

What is the drawback if two same objects have different hashcode

I know that different objects may have same hash code. But what if equal objects have different hashcode (just a curious question so don't ask me why i do so):

public class Myclass{
    int data = 0;
    @Override
    public boolean equals(Object obj) {
        return obj instanceof  Myclass && ((Myclass) obj).data == this.data;
    }
    @Override
    public int hashCode() {
        return (int)(Math.random()*1000);
    }
}

If you fail to satisfy equals-hashCode contract, then any algorithm or data structure which relies on this contract may work incorrectly. The examples of such data structures are HashMap , LinkedHashMap , ConcurrentHashMap , Hashtable (if your object is used as key), HashSet , LinkedHashSet .

Note that in your case the problem is even worse: you return different hashCode on the same object when hashCode method is invoked several times. So you don't even need two equal objects to break the collection. For example, such code usually prints false (though may occasionally print true):

public static void main(String[] args) {
    Myclass m = new Myclass();
    Set<Myclass> set = new HashSet<>();
    set.add(m);
    System.out.println(set.contains(m));
}

What you have in your code is not two equal objects with different hashcode, but an object that will return different hashcode on each invocation of hashcode() .

What will happen is that you wont be able to use this class in hashes- since you'll get different hashcode each time, you wont be able to get your object out from the hash, and also everytime you insert into the hash an object, it will be treated as non-existing in the hash

Hashcode is used in datastructures like HashMap or HashSet to determine where a particular object is going to be stored at. If two objects end up with the same hash code, then it results in a confusion when they are to be stored or retrieved from hash based structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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