简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM