字符串比较结果的差异b / w ==和字符串#替换为== [英] Difference in string comparison result b/w == and String#replace with ==

查看:205
本文介绍了字符串比较结果的差异b / w ==和字符串#替换为==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

字符串比较和Java中的字符串实习

我对Java中的字符串比较有一点疑问,请考虑以下代码:

I have small doubt regarding String comparisons in Java, consider the following code:

if("String".replace('t','T') == "String".replace('t','T')) {
  System.out.println("true");
}
else {
  System.out.println("false");
}

以上代码始终打印 false ,好像我这样尝试:

The above code always print's false, where as if I try like this:

if("STring" == "STring") {
  System.out.println("true");
}
else {
  System.out.println("false");
}

它总是打印我 true 。是的,我知道字符串比较应该用 String.equals()或equalsIgnoreCase()方法完成。但这是在采访中提出的问题之一,我很困惑。任何人都可以指导我这个行为吗?

It will always print me true. Yes, I know String comparisons should be done with String.equals() or equalsIgnoreCase() method. But this is one of the question was asked in interview and I am confused. Can anyone guide me on this behavior?

据我所知,在代码片段1中,String.replace('t','T ')返回对象,因此对象比较返回false。我是对的吗?

As per my knowledge, in code snippet 1, "String.replace('t','T') is returning object, so object comparisons returns in false. Am I right?

推荐答案


String.replace('t','T')返回对象,因此对象比较
返回false。我是对的吗?

"String.replace('t','T') is returning object, so object comparisons returns in false. Am I right?

是的,就这种情况而言,你是对的。 String#replace (或者任何String类的方法),将返回一个新的String对象(你可以猜到为什么? Immutability )。因此,你必须使用 equals 方法进行比较,以比较它们的内容。

Yes, as for this case, you are right. String#replace(or any method of String class for that matter), will return a new String object (You can guess why? Immutability). And thus you would have to do the comparison using equals method, to compare their contents.

现在,在第二种情况: -

Now, in the second case: -

"STring" == "STring"

您正在比较两个字符串文字。现在,由于在Java中字符串文字被实习,因此两个字面都相同(从某种意义上说,它们指向相同的内存位置),因此 == 比较会给你 true

You are comparing two string literals. Now, since String literals are interned in Java, so both the literals are same (in the sense, they point to the same memory location), and hence == comparison gives you true.

使用 == 等于进行比较的差异是, == 比较参考值 - 即对象的内存位置值,对于两个不同的字符串对象,这与第一种情况下的不同。然而,等于比较这些对象中的实际内容。

The difference in comparison using == and equals is that, == compares the reference value - i.e value of memory location of objects, which will be different for two different string objects, as you are having in first case. Whereas, equals compares the actual content in those objects.

这篇关于字符串比较结果的差异b / w ==和字符串#替换为==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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