[英]Difference between .equals (“0”) and .equals('0')
Context: 内容:
String comparison using equals with double quotes and single quotes 使用带双引号和单引号的等号进行字符串比较
I tried checking the value of the field "parentId" (String) of one of my business objects as below: 我尝试检查我的一个业务对象的字段“ parentId”(字符串)的值,如下所示:
System.out.println("Status 1 = "+myBusObj.getParentId().equals("0"));
System.out.println("Status 2 = "+myBusObj.getParentId().equals('0'));
I get the below output: 我得到以下输出:
Status 1 = true //where parentId was of value 0 (String)
Status 2 = false //where parentId was of value 0 (String)
Problem: Why Status 1 is true
but Status 2 is false
? 问题:为什么Status 1 is true
但Status 2 is false
?
The difference is that in the first case you are comparing with a one character String
, and in the second case you are comparing with a Character
object. 区别在于,在第一种情况下,您将与一个字符String
进行比较,在第二种情况下,您将与Character
对象进行比较。
Strings and Characters are not comparable using equals(Object)
; 使用equals(Object)
不能比较字符串和字符; hence the false
in the second case. 因此在第二种情况下为false
。
(There is a slight subtlety here ... in that '0'
is a char
literal that is being autoboxed to give you the Character
object. Prior to Java 5 where autoboxing was added to the language, the .equals('0')
call would be a compilation error. This is one of those examples where autoboxing is actually a hinderance ...) (这里有个细微的差别 ……因为'0'
是一个char
文字,将被自动装箱以提供Character
对象。在Java 5之前,自动装箱已添加到该语言中, .equals('0')
调用将是编译错误。这是自动装箱实际上是一个障碍的示例之一)
Status 1 : You try to compare string object to string object("String" String object) so result will be true. 状态1:您尝试将字符串对象与字符串对象(“ String”字符串对象)进行比较,因此结果为true。
Status 2 : You try to compare string object to character object('Character' character object) so that result will be false. 状态2:您尝试将字符串对象与字符对象(“字符”字符对象)进行比较,以使结果为false。
Thanks. 谢谢。
双引号将字符串括起来,单引号将字符括起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.