java - 将 String 和 Integer 与 equals 进行比较

标签 java string integer

下面代码的输出是false

String str = "3456";
String str1 = "3456";
System.out.println(Integer.valueOf(str).equals(str1));

我没看懂。我认为它会返回 true。在我准备 SCJP 时,了解其背后的原因可能会有所帮助。有人可以帮忙吗?

最佳答案

Integer 永远不会等于 String

这两个类都有非常严格的equals() 定义,接受它们各自类型的对象。

  • Integer.equals() :

    The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

  • String.equals() :

    The result is true if and only if the argument is not null and is a String 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/

相关文章:

java - equals() 和 hashCode() 的区别

python - 删除换行符时遇到问题

C 动态数据说明符

integer - 操作数的类型无效 "+"Ada 95

java - 在 Java 中检测 CapsLock

java - 生成给定大小的文件

java - 如何确定字符串是否可以使用 jodatimes DateTime 构造函数进行解析?

python - 如何在 Python 中比较区分大小写的字符串?

java - int 对象到整数转换的问题

java - 我如何获取存储到 android 中的文件中的所有 logcat 条目