[英]Every time I use String, does it create a new String object?
Let's say that I need to iteratively retrieve a value of the same key from a Java hashmap. 假设我需要从Java hashmap迭代地检索相同键的值。
for(int i=0; i<INTEGER.MAX; i++)
map.get("KEY");
In this case, is the "KEY" string created every time I call map.get("KEY")? 在这种情况下,每次调用map.get(“KEY”)时都会创建“KEY”字符串吗? I was wondering if it's always better to have a String constant, or it doesn't matter. 我想知道是否总是更好地拥有一个String常量,或者无关紧要。
No. String constants are interned automatically, so any identical string literals all reference the same object in memory. 不会。字符串常量会自动实现,因此任何相同的字符串文字都会引用内存中的相同对象。
Some more information on this: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3 关于此的更多信息: http : //www.xyzws.com/Javafaq/what-is-string-literal-pool/3
An example of this: 一个例子:
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
Yes/No Answer depends on how you create String Objects. 是/否答案取决于您如何创建字符串对象。 Below are the four scenarios I can think of as of now. 以下是我现在可以想到的四种情景。
Yes Cases 是的案例
No Cases 没有案例
is the "KEY" string created every time I call map.get("KEY")? 是每次调用map.get(“KEY”)时创建的“KEY”字符串?
No. 没有。
Java Strings are immutable, which allows the Java compiler to use a single instance for all string literals. Java字符串是不可变的,它允许Java编译器对所有字符串文字使用单个实例。 That is: all identical string literals in your program will reference a single string object. 也就是说:程序中所有相同的字符串文字都将引用单个字符串对象。
In the rare cases you need identical strings to be wrapped in two separate objects, you must explicitly instantiate a String object: 在极少数情况下,您需要将相同的字符串包装在两个单独的对象中,您必须显式实例化String对象:
String s1 = "bla";
String s2 = "bla";
// s1 == s2
String s3 = new String ("bla");
// s1 != s3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.