Why do we need to rewrite equals and hashcode in Java, and why can’t we use the object class to implement them

Guys, please let me know why we need to override equals and hashcode in the real world, and we can't use equals and hashcode of object

Solution

Object's equals / hashcode implementation is good - if you want a "reference ID" as your equality In other words, the on object will always be equal to itself, but different from another object

However, if you want two different objects to be equal, you must override the method to explain how they should be equal (and then rewrite the hash code to make it consistent)

Perhaps the simplest example is string Two different strings with the same characters are equal, and their equality is useful:

String x = new String(new char[]{'a','b','c'});
String y = new String(new char[]{'a','c'});
System.out.println(x.equals(y)); // Prints true

Now compare it to FileInputStream – what makes two fileinputstreams equal? What if they are reading the same document? What about the location in the file? How about two streams to different files with the same content? It doesn't make much sense for IMO to raise this question

Now, how does the object implementation know the difference between the required behavior of FileInputStream and string? It may notice that annotations added to fields, properties and types themselves may automatically generate appropriate bytecode, and then JIT compilation can be performed... But of course Java appeared long before annotations were available The current method is very simple - but it does mean that if you want the values of different objects to be equal, you need to write your own code

It's important to note that for immutable types, it's usually easier to consider equality - it's strange if two objects are equal at a point in time and then not equal later This can also seriously mess up the hash table – the hash code should basically depend on aspects of objects considered equal, and the hash code is recorded when the key is first added to the hash table; If you subsequently change the contents of the key, its hash code will change, but the hash table will not know it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>