Java新的String和新的StringBuilder的堆行为 [英] Java new String and new StringBuilder in heap behavior

查看:108
本文介绍了Java新的String和新的StringBuilder的堆行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 字符串池是否驻留在堆上?如果是,字符串是否符合垃圾回收的条件?

当使用 new String(abc),我们知道它在堆上创建了一个对象,并将字符串文字放置在字符串池中。所以我的第二个问题是:


  1. 是否存在 new StringBuilder(abc)的行为方式与 new String(abc)相同?如果是的话,StringBuilder如何处理字符串池中的字符串字面值?


解决方案

混淆编译时间,加载时间和运行时间。

字符串文字在类加载时添加到常量池中。只要在类代码中的任何地方提及就足够了;您甚至不必在该类中执行任何代码行。

另一方面,表达式 new String(literal )会在每次评估时产生一个新的字符串实例。该实例与常量池中的实例不同,并且具有字符串值的副本。



StringBuilder acts与 String 在这方面完全一样:它使用字符串值的副本进行初始化。


  1. Does the String pool reside on the heap? If yes, are String literals eligible for garbage collection?

When using new String("abc"), we know that it creates an object on the heap and places the String literal in the String pool. So my 2nd question is:

  1. Does new StringBuilder("abc") behave the same way as new String("abc") ? If yes, how does StringBuilder manipulate the String literal inside the String pool?

解决方案

You are confusing compile time, load time, and runtime.

A string literal is added to the constant pool at class loading time. Just a mention of a literal anywhere in the class code is enough; you don't even have to execute any line of code in that class.

On the other hand, the expression new String("literal") yields a new String instance each time it is evaluated. That instance is distinct from the one in the constant pool and has a copy of the string value.

StringBuilder acts exactly the same way as String in this respect: it is initialized with a copy of the string literal's value.

这篇关于Java新的String和新的StringBuilder的堆行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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