【问题标题】:What is the difference between new String("ONE") and String one = "ONE" in java? [duplicate]java中的new String("ONE")和String one = "ONE"有什么区别? [复制]
【发布时间】:2011-11-28 11:37:57
【问题描述】:

可能重复:
Java Strings: “String s = new String(”silly“);”

我正在浏览一些字符串示例,我很困惑:

有什么区别

String one = new String("ONE");

和

String one = "ONE";

这就是为什么我有点困惑的例子

String one = new String("ONE");
String another_one = new String("ONE");
System.out.print(one.equals(another_one)); //-->true
System.out.print(one == another_one );     //-->false

同时

  String one = "ONE";
  String another_one = "ONE";
  System.out.print(one.equals(another_one)); //-->true
  System.out.print(one == another_one );     //-->true

为什么会这样?

【问题讨论】:

标签: java string


【解决方案1】:
String one = new String("ONE");

创建一个新对象。使用 equals 方法比较字符串本身,当它们完全相同时返回 true。使用“==”运算符进行比较会比较对象,在这种情况下,由于您创建了一个新对象,所以这些对象并不相同。

String one = "ONE";
String another_one = "ONE";  

这实际上并没有创建一个新对象,编译器将优化这两个语句,以便 "one" 和 "another_one" 都指向内存中的同一个对象,因为它们都引用同一个字符串字面量。由于这里两个变量都指向同一个对象,因此“==”在这种情况下将返回 true。

【讨论】:

    【解决方案2】:

    litera ONE 编译后变为常量。也就是说,在情况二中,两个字符串指的是同一个位置。也就是说,他们是平等的。在第一种情况下, another_one 对象明确地是内容为 ONE 的新对象。 剂量是有道理的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 2012-12-29
      • 2015-12-07
      • 1970-01-01
      • 2013-12-03
      • 2021-04-15
      • 2014-07-22
      相关资源
      最近更新 更多