假设我需要从 Java HashMap 中迭代地检索相同键的值。
for(int i=0; i<INTEGER.MAX; i++)
map.get("KEY");
在这种情况下,每次调用 map.get("KEY") 时是否都创建了“KEY”字符串?我想知道拥有一个 String 常量是否总是更好,或者这无关紧要。
最佳答案
没有。字符串常量会自动驻留,因此任何相同的字符串文字都引用内存中的同一个对象。
关于此的更多信息:http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3
一个这样的例子:
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
关于java - 每次我使用 String 时,它都会创建一个新的 String 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704896/