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

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

问题描述

可能重复:
使用new创建字符串对象并将其与intern进行比较方法

Possible Duplicate:
String object creation using new and its comparison with intern method

我在和Strings一起玩耍以进一步理解它们,我注意到一些我无法解释的内容:

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 ?

最后一行如何显示为真?这意味着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天全站免登陆