为什么 Java equals(Object O) 方法没有可以将特定对象类型(例如字符串、整数等)作为输入的变体?

Why does the Java equals(Object O) method not have a variant which can take a specific object type (e.g. String, Integer, etc) as input?

我遇到了需要使用 Java 语言比较 equality/non-equality 的两个字符串(或任何其他对象)的问题。 String Object 上有两种方法对此非常有用,即。 compareTo(Object O),其中 returns 是整数比较结果,而其他 equals(Object o),其中 returns 是布尔值。 我的问题是,虽然 compareTo() 有一个变体,它采用特定字符串而不是通用对象作为输入,但为什么 equals() 没有这样的变体? 我经常遇到的一个问题是,当我在对象上调用 equals 方法并将通用对象作为参数传递时,它不会抛出任何编译错误。 考虑下面的代码片段(这不是现实生活中的例子,但我写这些只是为了阐明我的观点)。

String testStr = new String("1");
Integer testInt = new Integer(1);

testStr.compareTo(testInt.toString()); // compiles
testStr.equals(testInt.toString());    // compiles

testStr.equals(testInt);               // compiles and will be always false 
testStr.compareTo(testInt);            // doesn't compile

因为equals()是在Object中声明的,而compareTo(T foo)是在Comparable<T>中定义的。

在泛型出现之前,问题与 ComparablecompareTo 采用对象参数相同,但由于没有“Equalable”接口,因此没有地方可以粘贴泛型参数.