why we need to override equals and hashcode in jav

2019-01-15 11:38发布

问题:

guys please let me know, in real world why we need to override equals and hashcode and cant we use Object's equals and hashcode.

回答1:

Object's equals/hashcode implementation is fine - if you want "reference identity" as your equality. In other words, on object will always compare as equal to itself, but different to another object.

If, however, you want two distinct objects to be equal, you've got to override the method to say how they should be equal (and then override hashcode to be consistent with that).

The simplest example is probably String. Two different strings with the same characters are equal, and it's very useful for them to be equal:

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

Now compare that to FileInputStream - what would make two FileInputStreams equal? If they're reading the same file? What about the position within the file? What about two streams to different files with the same content? It doesn't really make a lot of sense to ask the question, IMO.

Now, how could the Object implementation know the difference between the desired behaviour of FileInputStream and String? It could potentially take note of annotations added to fields, properties and the type itself, possibly autogenerating appropriate bytecode which could then get JIT-compiled... but of course Java came out long before annotations were available. The current approach is very simple - but it does mean if you want value equality for distinct objects, you need to code it yourself.

One point to note is that equality is usually easier to think about for immutable types - it is odd if two objects are equal at one point in time and then non-equal later on. This can also seriously mess up hashtables - the hashcode should basically depend on the aspects of the object which are considered for equality, and the hashcode is recorded when a key is first added to a hashtable; if you then change the contents of the key, its hashcode would change, but the hashtable wouldn't know about it.



回答2:

Because in real world if you use Object's implementation

new Integer( 1 ) is NOT equal to new Integer( 1 )