具有相同参考的字符串Concat? [英] String Concat With Same Reference?

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

问题描述

这是我的代码,现在我对输出的字符串池和
堆存储感到非常困惑。

Here is my code and I am now quite confuse about String pool and Heap storage by this output.

public class String1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String str = "abcd";
        String str1 = "" ;

        str1=str1+"abcd";

        if(str.equals(str1))
            System.out.println("True");
        else
            System.out.println("False");

        if(str == str1)
            System.out.println("True");
        else
            System.out.println("False");
    }
}

现在,我正在创建String str 并将其存储在字符串池中(如果我输入错误,请更正!)。
现在,在concat str1 和字符串 abcd 之后,它们都具有相同的值。
因此,我认为 str 和str1在字符串池中应具有相同的引用,因此,第二个 if 语句应该打印 true ,但是打印 false

Now, I am creating String str and will be stored in string pool (Correct me if I am getting wrong!). Now after concat str1 with string "abcd" they both have same value. So, I think str and str1 should have same reference in String pool and So, 2nd if statement should print true but it prints false.

所以,我的问题是为什么str和str1没有得到相同的引用?

So, my question why str and str1 not getting same reference ?

推荐答案

Java自动 interns (是指,将它们放入字符串池)字符串文字,而不是新创建的字符串。另请参见 https://stackoverflow.com/a/1855183/1611055

Java automatically interns (means, puts them into the String pool) String literals, not newly created Strings. See also https://stackoverflow.com/a/1855183/1611055.

请记住,字符串是不可变的,因此 + 运算符必须创建一个新的String-不能追加到现有的String上。在内部, + 运算符使用 StringBuilder 连接字符串。最终结果是通过 StringBuilder.toString()检索的,该结果实际上是返回新的String(value,0,count);

Remember that Strings are immutable, so the + operator must create a new String - it can not append to the existing one. Internally, the + operator uses a StringBuilder to concatenate the strings. The final result is retrieved through StringBuilder.toString() which essentially does return new String(value, 0, count);.

此新创建的字符串不会自动放入字符串池中。

This newly created String is not automatically put into the String pool.

因此 str1 引用与 str 的引用不同,即使字符串的内容相同。 str 指向字符串池中的位置,而 str1 指向堆中的位置。

Hence the str1 reference is different from str even though the strings have the same content. str points to a location in the string pool, while str1 points to a location on the heap.

如果添加

str1 = str1.intern();

str1 = str1 + abcd之后; 要显式实习新创建的String,则第二个 if 语句返回 true

after str1 = str1 + "abcd"; to explicitly intern the newly created String, your second if statement returns true.

或者, str1 =(str1 + abcd)。intern(); 具有相同的效果。

Alternatively, str1 = (str1 + "abcd").intern(); would have the same effect.

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

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