String和new String有什么区别? [英] What's the difference between String and new String?
问题描述
这两个陈述之间的区别是什么:
What's the difference between these two statements:
String a1 = new String("abc");
和
String a2 = "abc";
如果你能说明差异,那就太棒了。
If you could illustrate the difference, that would be great.
推荐答案
第一个是创建一个新的String对象;第二个是有效地使用已经存在的(它是在加载类文件时创建的。)几乎没有理由使用 String(String)
构造函数。
The first one is creating a new String object; the second one is effectively using one which already exists (it's created while loading the class file.) There is virtually never a reason to use the String(String)
constructor.
(我说虚拟,因为有一种情况:如果你打破了巨大的 String
通过调用 substring()
然后丢弃原始文件,可以使用此构造函数创建新的 String
s来自子字符串。但这确实是一个不起眼的案例。)
(I say virtually because there is one case: if you're breaking up a huge String
by calling substring()
and then discarding the original, you can save memory by using this constructor to create new String
s from the sub-strings. That's really an obscure case, though.)
这篇关于String和new String有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!