将两个字符串与“==”进行比较:它何时起作用? [英] Comparing two strings with "==": when will it work?

查看:158
本文介绍了将两个字符串与“==”进行比较:它何时起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有三个字符串,

String s1 = "string one";
String s2 = new String("string one");
String s3 = "string one";

我知道 s1 == s2 false ,但我在某处读到 s1 == s3 true 。它是否正确?为什么或为什么不呢?

I know it is true that s1 == s2 is false, but I read somewhere that s1 == s3 is true. Is this correct? Why or why not?

推荐答案

字符串文字自动实现。因此s1 == s3为真。字符串可以在字符串常量池中创建,也可以在堆空间中创建。如果您实际在堆中创建了一个字符串,则该字符串将位于字符串常量池中。

String literals are interned automatically. Hence s1 == s3 is true. Strings can either be created in the string constant pool or they can be created in the heap space. If you intern a string created in the heap, the string will be in the string constant pool.

创建字符串文字(String s1 =string one)时,字符串将在字符串常量池中创建。此外,字符串常量池不存储重复项。所以当你说,

When you create a string literal (String s1 = "string one"), the string is created in the string constant pool. Additionally, the string constant pool doesn't store duplicates. So when you say,

String s1 = "string one";
String s3 = "string one";

s1和s3都将指向字符串常量池中字符串的同一实例。所以s1.equals(s3)将是真的。而s1 == s3也是如此;因为两个指针都是相同的。

Both s1 and s3 will be pointing to the same instance of the string in the string constant pool. So s1.equals(s3) will be true. And s1 == s3 also is true; since both the pointers are the same.

然而,当你使用new构造函数实例化一个字符串时

However, when you instantiate a string using the "new" constructor

String s2 = new String("string one");

然后在堆空间中创建s2。堆空间是与字符串常量池不同的内存区域

then s2 is created in the heap space. The heap space is a different area of memory than the string constant pool

因此,当s1.equals(s2)为真时,s1 == s2为false;因为它们将指向不同的内存区域。

So while s1.equals(s2) is true, s1 == s2 is false; since they will be pointing to different areas of memory.

但是,您可以转换使用new构造函数创建的字符串,以使其移动到字符串常量池中调用intern()函数。所以 s2.intern()将在字符串常量池中返回一个字符串;虽然s2最初是在堆中创建的。

However, you can convert a string created using the "new" constructor to make it move to the string constant pool by invoking the intern() function. So s2.intern() will return a string in the string constant pool; although s2 was originally created in the heap.

这篇关于将两个字符串与“==”进行比较:它何时起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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