When overriding equals in Java, why does it not work to use a parameter other than Object?

后端 未结 7 1923
攒了一身酷
攒了一身酷 2020-12-03 18:13

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

相关标签:
7条回答
  • 2020-12-03 18:16

    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.

    0 讨论(0)
  • 2020-12-03 18:18

    there are different types of http://en.wikipedia.org/wiki/Polymorphism_(computer_science). java does not do http://en.wikipedia.org/wiki/Double_dispatch.

    0 讨论(0)
  • 2020-12-03 18:18

    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.

    0 讨论(0)
  • 2020-12-03 18:20

    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).

    0 讨论(0)
  • 2020-12-03 18:29

    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.

    0 讨论(0)
  • 2020-12-03 18:34

    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.

    0 讨论(0)
提交回复
热议问题