Java string pool – how to store strings on the heap

See English answers > what is the Java string pool and how is "s" different from new string ("s")? 5

String s1 = "Hello world"
String s2 = "Hello world XXX"

I guess these strings store two strings in the Java string pool:

>Hello World XXX

How are these strings stored in the memory of the string pool on the heap? Is it stored in a special heap in the string pool? Does the SP have any string indexes, or are these strings stored in an ordered collection? What happens if "Hello World AAA" is added to the SP? thank you.

Solution

Strings are immutable For your example, there will be 2 objects in the string pool If you want to know about creation, here is a very good post with a simple explanation: http://www.journaldev.com/797/what-is-java-string-pool.

If you will use:

String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Hello WorldXXX";

Then there will be two objects, one for Hello world, so S1 = = S2; Is true (the same object), but Hello worldxxx will be another object in memory

The string stored in memory is defined by string interning. Here is the decdescription of the wiki

For your comment: if you call operator new, it depends on that, because it is created in heap space (outside string pool) If you use it in my example, they are stored in the string pool, where it is decided that if it already exists in the string pool, they are like objects (the memory in the string pool is the same)

Also try checking https://en.wikipedia.org/wiki/Flyweight_pattern

The above is the Java string pool - how to store all the string contents on the heap - collected and sorted by the programming house for you. I hope this article can help you solve the program development problems encountered by Java string pool - how to store strings on the heap.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>