Java 中 new String() 和 new String("") 初始化字符串有什么区别?

What is the difference between String initializations by new String() and new String("") in Java?

Java下面两个初始化有什么区别?

  1. String a = new String();
  2. String b = new String("");

Java Docs解释得很漂亮

这是 2 个不同的构造函数调用

public String()

Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.

public String(String original)

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

在第一种情况下,您只创建一个 String 对象,在第二种情况下:""new String,如果 "" 对象不存在于字符串池中。

  1. Initializes a newly created String object so that it represents an empty character sequence.

  2. Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

在内部,将调用不同的构造函数。

但是,生成的 String 对象的内容相同 相等(a.equals(b) 将 return true )

第一个是调用默认构造函数,第二个是调用复制构造函数,以便在每种情况下创建一个新字符串。

嗯,他们几乎一样

public static void main(String[] args) {
    String s1 = new String();
    String s2 = new String(""); 
    System.out.println(s1.equals(s2)); // returns true.
}

细微差别(相当微不足道):

  1. new String(); 的执行时间比 new String(""); 少,因为复制构造函数做了很多事情。

  2. new String("") 将空字符串 ("") 添加到字符串常量池中(如果它不存在)。

除此之外没有其他区别

注意:new String("abc") 的使用几乎总是不好的,因为您将创建 2 个字符串,一个在字符串常量池上,另一个在具有相同值的堆上。

TheLostMind 大部分是正确的,但我想补充一点,复制构造函数实际上并没有做那么多:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/lang/String.java#137

137  public String() {
138 this.value = new char[0];
139 }

151 public String(String original) {
152 this.value = original.value;
153 this.hash = original.hash;
154 }

使用常量""无论如何都会使用第一个构造函数来创建对象引用,所以使用哪个并不重要。

无论如何,我建议使用字符串文字 "",因为如果您在别处使用该字符串,则可以保存对象引用。仅当您确实需要未在其他任何地方使用的该字符串的副本时才使用 String 构造函数。

从纯实用的角度来看,这些结构之间存在 差异,因为从来没有任何理由使用它们中的任何一个。它们既浪费又过于复杂,因此同样毫无意义。

要用空字符串初始化变量,请执行:

String s = "";

输入起来更短更简单,并且避免创建 any String 对象,因为在实习生池中的一个共享 "" 实例肯定已经被加载无论如何,其他人 class。