用等号比较String和Integer [英] Comparing String and Integer with equals

查看:658
本文介绍了用等号比较String和Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的输出为 false

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

我不明白。我以为它会返回 true 。在我为SCJP做准备时,理解它背后的原因可能会有所帮助。有人可以帮忙吗?

I didn't understand it. I thought it will return true. As I am preparing for SCJP, understanding the reason behind it may be helpful. Can someone please help?

推荐答案

整数永远不会等于字符串

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

Both classes have very strict equals() definitions that only accept objects of their respective types.


如果和,结果为true仅当参数不是 null 是包含相同int的 Integer 对象时值作为此对象。

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()


    当且仅当参数不是 null 是a时,结果才为真 S研ng object ,表示与此对象相同的字符序列。

    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()的一种非常常见的方式:只有同一类的对象(有时是子类)才能平等。其他实现是可能的,但也是例外。

    That's actually a quite common way to implement equals(): only objects of the same class (and occasionally subclasses) can be equal. Other implementations are possible, but are the exception.

    一个常见的例外是集合例如 List :每 遵循约定的实现将与任何其他实现进行比较时返回 true ,如果它具有相同的内容以相同的顺序。

    One common exception are the collections such as List: every List implementation that follows the convention will return true when compared to any other implementation, if it has the same content in the same order.

    这篇关于用等号比较String和Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆