I come across problems where I need to compare two strings (or any other object ) for equality/non-equality using Java language. There are two methods on String Object very useful for this purpose viz. compareTo(Object O), which returns a integer result of comparison while other equals(Object o), which returns a boolean. My question is while there is a variant for compareTo() which takes a specific String as input instead of an generic Object, why there is no such variant for equals() ? One issue that I often come across is when I invoke equals method on an object and passes generic object as an argument it doesn't throw any compile error. Consider the code snippet below (this is not a real life example but I have written to just make my point clear).

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
1

There are 1 answers

5
Kayaman On BEST ANSWER

Because equals() is declared in Object and compareTo(T foo) is defined in Comparable<T>.

Before generics the issue was the same with Comparable, compareTo taking an Object argument, but since there's no "Equalable" interface there was no place to stick the generic parameter.