Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ArrayDeque override equals() and hashCode()?

EDITED: Now only ArrayDeque is considered. (I originally thought LinkedList also doesn't override the two methods.)

Collection type ArrayDeque simply uses the hashCode and equals method implementations that it inherits from Object.

Why doesn't it instead override these methods with proper implementations (i.e. hash and equality test based on contained elements)?

like image 560
Pouria Avatar asked Aug 13 '13 08:08

Pouria


People also ask

Is it necessary to override hashCode and equals method?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

What happens if we don't override equals and hashCode?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Which class does not override the equals () and hashCode () methods inheriting them directly?

Q1. Which String class does not override the equals() and hashCode() methods, inheriting them directly from class Object? Ans. java.


1 Answers

LinkedList extends AbstractSequentialList which extends AbstractList which does override equals and hashCode - so the implementation is not inherited from Object.

ArrayDeque, on the other hand, really doesn't inherit anything other implementation as far as I can see. Its direct superclass (AbstractCollection) doesn't override them. This feels like an exception rather than the rule - I believe most collection implementations in Java "do the right thing".

I don't know of the justification for ArrayDeque choosing not to implement equality, but if you want to compare two deques you could easily just convert them into lists or arrays and do it that way.

like image 194
Jon Skeet Avatar answered Sep 21 '22 23:09

Jon Skeet