下面代码的输出是false
String str = "3456";
String str1 = "3456";
System.out.println(Integer.valueOf(str).equals(str1));
我没看懂。我认为它会返回 true
。在我准备 SCJP 时,了解其背后的原因可能会有所帮助。有人可以帮忙吗?
最佳答案
Integer
永远不会等于
String
。
这两个类都有非常严格的equals()
定义,只接受它们各自类型的对象。
-
The result is true if and only if the argument is not
null
and is anInteger
object that contains the same int value as this object. -
The result is true if and only if the argument is not
null
and is aString
object that represents the same sequence of characters as this object.
这实际上是实现 equals()
的一种非常常见的方法:只有同一类(有时是子类)的对象可以相等。其他实现也是可能的,但属于异常(exception)情况。
一个常见的异常(exception)是集合 such as List
: 与任何其他 实现相比,每个遵循约定的List
实现都将返回true
,如果它具有相同顺序的相同内容。
关于java - 将 String 和 Integer 与 equals 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17546466/