两个字符串应该相等? [英] Both strings should be equal?

查看:129
本文介绍了两个字符串应该相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String s1 = "learn";
String s1 = s1+"Java";

现在s1指向learnJava字符串对吗?

now s1 is pointing to "learnJava" string right ?

String s2 = "learnJava";

if(s1 == s2)是假。为什么?

s2 应指向相同的learnJava因为它已经存在于StringConstantPool(s1)中。

s2 should point to same "learnJava" as its already present in StringConstantPool(s1).

推荐答案


s2应指向相同的learnJava 因为它已经存在于StringConstantPool中。

s2 should point to same "learnJava" as its already present in StringConstantPool.

Nope - 字符串池仅用于常量字符串,除非你打电话给实习生

Nope - the string pool is only used for constant strings unless you call intern.

所以字符串池包含learnJavalearnJava ...但是 s1 引用字符串池中的字符串而不是,因为连接是在执行时执行的。

So the string pool contains "learn", "Java" and "learnJava"... but s1 refers to a string not in the string pool, because the concatenation is performed at execution time.

如果你有编译时常量表达式,它会有所不同:

If you had a compile-time constant expression, it would be different:

String s1 = "learn" + "Java"; // Constant expression
String s2 = "learnJava";
System.out.println(s1 == s2); // true, guaranteed

或者如果你想保持执行时间连接:

Or if you want to keep your execution-time concatenation:

String s1 = "learn";
s1 += "Java";
s1 = s1.intern();
String s2 = "learnJava";
System.out.println(s1 == s2); // true

一般来说,只是不要将字符串与 =进行比较= = ......这几乎总是一个坏主意。

In general though, just don't compare strings with ==... it's almost always a bad idea.

这篇关于两个字符串应该相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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