java中字符串的可重用性? [英] Reusability of Strings in java?

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

问题描述

String h = "hi";

这里我们将字符串h引用到字符串文字hi。 JVM有一个字符串文字池来存储字符串文字,所以我们可以重用字符串,因为它们是不可变的...

here we are referencing string h to string literal hi. JVM has a string literal pool to store string literals so we can reuse the strings as they re immutable...

当我们说可重用时,这是什么意思?我们在谈论地址吗?从相同的地址evey时间中选出它?

When we say reusable, what is the exact meaning of this? are we talking about the address ? that it is picked from same address evey time ?

推荐答案

是的,为了简单起见你可以把它想象成从同一地点采摘地址,但更精确的变量是持有相同的引用 - JVM可用于映射到对象的正确内存地址的标识符(因为对象可以在内存中移动)。

Yes, to make things simpler you can think of it as picking from same address, but to be more precise variables are holding same reference - identifier which JVM can use to map to proper memory address of object (since objects can be moved in memory).

您可以通过以下代码进行测试:

You can test it by code like this:

String w1 = "word";
String w2 = "word";
String b = new String("word"); // explicitly creating String by calling `new` operator 
                               // won't put it in string pool
System.out.println(w1 == w2);  // true  -> variables hold same reference
System.out.println(w1 == b);   // false -> variable hold different references
b = b.intern(); // check if pool contains this string, if not put this string in pool, 
                // then return reference of such string from pool and store it in b variable
System.out.println(w1 == b);   // true  -> now w1 and b hold same reference

这篇关于java中字符串的可重用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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