问题描述
String str = new String("Hello");
通常情况下,我在互联网上的许多文章中都读到,当我们写这篇文章时会创建两个对象。上面的陈述。在堆上创建一个String对象,并在Literal Pool上创建一个字符串对象。并且堆对象也引用在Literal Pool上创建的对象。 (如果错误,请更正我的陈述。)
Normally I have read, in many articles available on internet, that two objects are created when we write the statement above. One String object is created on the heap and one string object is created on the Literal Pool. And the heap object is also referring the object created on Literal Pool. (Please correct this statement of mine if it is wrong.)
请注意,上述解释是根据我的理解,在阅读了一些互联网上的文章之后。
Please note that the above explanation is as per my understanding after reading some articles on internet.
所以我的问题是..是否有任何方法可以停止在文字池中创建字符串对象。怎么做?
So my question is.. Are there any ways available to stop creating the string object in literal pool. How it can be done?
[请告诉我有关理解这个文字池的最佳链接,如何实施]
[Please let me know about the best link for understanding of this Literal Pool, How is it implemented]
推荐答案
如果我正确理解你的问题,你会问如何初始化一个字符串而不将其放在字符串文字池中。只要不声明字符串文字表达式,就可以避免这种情况(不要用双引号声明一系列字符。)
If I understand your question correctly, you're asking how to initialize a string without placing it in the string literal pool. You can avoid this as long as you don't declare a string literal expression (don't declare a series of characters in double quotes.)
// these two strings will be placed in the string literal pool
String one = "one";
String two = new String("two");
// this third string will NOT be placed in the string literal pool
String three = new String(new char[] {'t', 'h', 'r', 'e', 'e'});
这篇关于字符串文字池如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!