为什么相等的java字符串采用相同的地址? [英] Why are equal java strings taking the same address?

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

问题描述

可能的重复:
使用 new 创建字符串对象及其与 intern 的比较方法

我正在玩弄字符串以更深入地了解它们,但我注意到一些我无法解释的事情:

I was playing around with Strings to understand them more and I noticed something that I can't explain :

String str1 = "whatever";
String str2 = str1;
String str3 = "whatever";
System.out.println(str1==str2); //prints true...that's normal, they point to the same object
System.out.println(str1==str3); //gives true..how's that possible ?

最后一行如何给出 true ?这意味着 str1 和 str3 在内存中具有相同的地址.

How is the last line giving true ? this means that both str1 and str3 have the same address in memory.

这是一种编译器优化,它足够聪明以检测两个字符串文字是否相同(随便"),从而将 str1 和 str3 分配给同一个对象?还是我在字符串的底层机制中遗漏了什么?

Is this a compiler optimization that was smart enough to detect that both string literals are the same ("whatever") and thus assigned str1 and str3 to the same object ? Or am I missing something in the underlying mechanics of strings ?

推荐答案

http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3

正如帖子所说:

字符串分配,就像所有的对象分配一样,在时间和内存上都被证明是昂贵的.JVM 在实例化字符串文字时会执行一些技巧以提高性能并减少内存开销.为了减少在 JVM 中创建的 String 对象的数量,String 类保留了一个字符串池.每次您的代码创建一个字符串文字时,JVM 首先检查字符串文字池.如果该字符串已存在于池中,则返回对池化实例的引用.如果池中不存在字符串,则实例化一个新的 String 对象,然后放入池中.

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.

这篇关于为什么相等的java字符串采用相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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