I ran into an interesting behavior recently. It seems that if I override .equals() to take a parameter other than Object, it doesn\'t get called. Can anyone explain to me
Ok let me re-phrase.
(1)Because the compiler eliminates all information regarding to Generics (erasure, see here), and (2) because you cannot override a method without the exact same signature (equals(Object)), (3) during runtime all objects inside the List are treated as Objects and not as instances of MyClass. Hence, the method that gets called is equals(Object) since this is the one that is been overwritten by your class.
there are different types of http://en.wikipedia.org/wiki/Polymorphism_(computer_science). java does not do http://en.wikipedia.org/wiki/Double_dispatch.
The ArrayList implementation of the contains(Object) method is bound to use Object.equals(Object) method internally, so it'll never know about your overloading of the equals(MyClass) method. Only an overriding method (with matching signature) will be found.
equals(Object) is overriding a super method; you can not override a super method without using the exact same signature (Well, there are some exceptions like covariant returntypes and exception).
You're mixing up "overriding" and "overloading".
Overriding -- adding a replacement definition of an existing method for purposes of polymorphism. The method must have the same signature. The signature consists of the name and argument types. Overridden methods are selected at runtime based on the runtime type of the target object.
Overloading -- adding a method with the same name but a different signature. Overloaded methods are selected at compile time based on the compile time type of the target object.
You're assuming that the contains()
method in List
knows the type of the object at runtime, which is incorrect.
Because of erasure, List<MyClass>
becomes just a regular List
at runtime, so the contains()
method sees its parameter as an Object
, thus invoking Object's equals()
instead of the one you defined for MyClass
in its execution.