Java – does it create a new string object every time I use string?

Suppose I need to iteratively retrieve the value of the same key from Java HashMap

for(int i=0; i<INTEGER.MAX; i++)   
          map.get("KEY");

In this case, every time you call map Will the "key" string be created when get ("key")? I wonder if it's always better to have a string constant, or it doesn't matter

Solution

can't. String constants are implemented automatically, so any same string literal references the same object in memory

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

An example:

String s1 = "Test";
String s2 = "Test";
String s3 = new String("Test");
s1 == s2;//Evaluates to true,because they are the same object (both created with string literals)
s1 == s3;//Evaluates to false,because they are different objects containing identical data
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
分享
二维码
< <上一篇
下一篇>>