“文本”之间的区别是什么?和新的字符串(“text”)? [英] What is the difference between "text" and new String("text")?

查看:203
本文介绍了“文本”之间的区别是什么?和新的字符串(“text”)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个陈述之间有什么区别?

What is the difference between these two following statements?

String s = "text";

String s = new String("text");


推荐答案

new String(text );
显式创建 String 对象的新的和引用不同的实例; String s =text; 可以重用字符串常量池中的实例(如果有的话)。

new String("text"); explicitly creates a new and referentially distinct instance of a String object; String s = "text"; may reuse an instance from the string constant pool if one is available.

很少想要使用 new String(anotherString)构造函数。来自API:

You very rarely would ever want to use the new String(anotherString) constructor. From the API:


String(String original) :初始化新创建的 String 对象,以便它表示与参数相同的字符序列;换句话说,新创建的字符串是参数字符串的副本。除非需要显式的原始副本,否则不必使用此构造函数,因为字符串是不可变的。

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.



相关问题




  • Java字符串:String s = new String(傻);

  • 字符串是Java中的对象,为什么我们不使用'new'来创建它们?

  • Related questions

    • Java Strings: "String s = new String("silly");"
    • Strings are objects in Java, so why don’t we use ‘new’ to create them?
    • 检查以下代码段:

          String s1 = "foobar";
          String s2 = "foobar";
      
          System.out.println(s1 == s2);      // true
      
          s2 = new String("foobar");
          System.out.println(s1 == s2);      // false
          System.out.println(s1.equals(s2)); // true
      

      == 关于两个参考types是参考标识比较。 等于的两个对象不一定是 == 。在引用类型上使用 == 通常是错误的;大部分时间等于需要改为使用。

      == on two reference types is a reference identity comparison. Two objects that are equals are not necessarily ==. It is usually wrong to use == on reference types; most of the time equals need to be used instead.

      尽管如此,如果出于某种原因需要创建两个等于但不是 == 字符串,你可以使用 new String(anotherString)构造函数。然而,需要再说一遍,这是非常特有的,很少是意图。

      Nonetheless, if for whatever reason you need to create two equals but not == string, you can use the new String(anotherString) constructor. It needs to be said again, however, that this is very peculiar, and is rarely the intention.

      • JLS 15.21.3 Reference Equality Operators == and !=
      • class Object - boolean Object(equals)
      • Java String.equals versus ==
      • How do I compare strings in Java?

      这篇关于“文本”之间的区别是什么?和新的字符串(“text”)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆