java String的不变性 [英] java String's immutability

查看:98
本文介绍了java String的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我跑步,

String s1="abc";

那么之间有什么区别

String s2=new String(s1);

String s2="abc";

这就是我感到困惑的地方:

Here's what I'm confused about:

Head First Java说:如果String池中已经存在一个具有相同值的String,则JVM不会创建重复项,它只是将您的引用变量引用到现有条目.认为s1已经创建了"abc",s2只是引用它.我说的对吗?

The Head First Java says:"If there's already a String in the String pool with the same value, the JVM doesn't create a duplicate, it simply refers your reference variable to the existing entry. " Which at my point of view is that the s1 has already created "abc",s2 just refers to it. Am I right??

推荐答案

字符串常量池在这种情况下进入图片,如下面的屏幕截图所示.

String Constant Pool comes into picture in this case as shown in below screenshot.

我认为它将帮助您直观地理解它.

I think it will help you to understand it visually.

String s1="abc"; // s1 will go to String constant pool

String s2=new String(s1); // any object created by "new" keyword will go to Heap

String s2="abc"; // s1 and s2 both will refer to same string in constant pool

这篇关于java String的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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