To me, equals() between objects of inconvertible types
is one of the most useful IntelliJ inspection.
It's almost never intended to have objects with different types equal to each other.
I understand equals
method was introduced prior to Java 5 so there is no generics to leverage. But even the new null safe Objects.equals
introduced by JDK7 is still not type safe. Am I missing some key consideration of this design?
By typesafe equals(), I mean something like public static <T> boolean equals(T a, T b)
. So that it becomes a compilation error rather then inspection warning.
====================================
added on 2018-11-17:
RE: user949300's answer. I understand there will be uncovered edge cases when we use a more restricted version of equals
. But in reality, most of the case by calling equals
we are really just comparing DTOs: are they having the same type and do they have the same properties? I am not suggesting we should always use the restricted version but it should help in 95% of the case as compiler can make things more obvious than IDE specific inspector.
foo.Equals(bar)
since foo and bar necessarily inherit from Object, the generic function infers Object to be T.