[英]Java: Beginner question regarding Strings
在Java中创建String时,这两者之间有什么区别:
String test = new String();
test = "foo";
和
String test = "foo";
我什么时候需要使用关键字new? 或者这两个基本相同,它们都创建一个新的String对象?
在第一个片段中,您创建一个新的空字符串,然后立即用字符串文字覆盖它。 您创建的新字符串将丢失,最终将被垃圾回收。
创建它是没有意义的,你应该只使用第二个片段。
new String()
将使用自己的标识哈希码创建对象字符串的新实例。 创建类似String string = "myString";
Java将尝试通过搜索已创建的字符串来重用该字符串,以获得该字符串。 如果找到,它将返回该字符串的相同标识哈希码。 这将导致,如果您创建例如字符串的标识哈希码,您将获得相同的值。
例:
public class Stringtest {
public static void main(String[] args) {
final String s = "myString";
final String s2 = "myString";
final String otherS = new String("myString");
//S and s2 have the same values
System.out.println("s: " + System.identityHashCode(s));
System.out.println("s2: " + System.identityHashCode(s2));
//The varaible otherS gets a new identity hash code
System.out.println("otherS: " + System.identityHashCode(otherS));
}
}
在大多数情况下,您不需要创建字符串的新对象,因为在处理HashMap
或类似事物时您没有静态值。
因此,只有在真正需要时才使用new String
创建新的字符串。 大多使用String yourString = "...";
。
这是一个示例程序,可帮助您了解字符串在Java中的工作方式。
import java.util.Objects;
public class TestStrings {
public static void main(String[] args) {
String test = new String();
System.out.println("For var test value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
test = "foo";
System.out.println("For var test after reassignment value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
String test2 = "foo";
System.out.println("For var test2 value is '"+ test2+ "' and object identity is "+ System.identityHashCode(test2));
String test3 = new String("foo");
System.out.println("For var test3 value is '"+ test3+ "' and object identity is "+ System.identityHashCode(test3));
}
}
运行此命令以查看为变量test
, test2
和test3
打印的标识哈希代码会发生什么。
基本上,Java会尝试优化字符串在创建为文字时的创建方式。 Java尝试维护字符串池,如果再次使用相同的文字,它将使用此字符串池中的相同对象。 这可以做到,因为java中的字符串是不可变的。
你可以在这个问题上进一步阅读什么是Java String interning?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.