[英]Does having a wrapper object return value (e.g. Integer) cause auto boxing in Java?
[英]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语言比较两个字符串(或任何其他对象)是否相等的问题。 为此,在字符串对象上有两种方法非常有用。 compareTo(Object O)
,返回比较的整数结果,而其他equals(Object o)
,返回布尔值。 我的问题是, compareTo()
有一个变体,它使用特定的String作为输入,而不是通用Object,为什么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>
定义。
在泛型之前, Comparable
的问题与使用Object参数的compareTo
相同,但是由于没有“ Equalable
”接口,因此没有地方可以粘贴泛型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.