Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

why we need to override equals and hashcode in java and why cannot we use Object class implementation

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...