【问题标题】:New String vs String s = "something" , what's the difference ? [duplicate]New String vs String s = "something" ,有什么区别? [复制]
【发布时间】:2014-05-01 13:30:55
【问题描述】:

考虑代码:

public class Strings {

    public static void createStr()
    {
        String s1 = new String("one");
        String s2 = "one";

        System.out.println(s1);
        System.out.println(s2);
    }

    public static void main(String args[])
    {
        createStr();
    }

}

String s1 = new String("one");String s2 = "one"; 有什么区别?

【问题讨论】:

    标签: java string new-operator


    【解决方案1】:
      String s1 = new String("one"); // will be created on the heap and not interned unless .intern() is called explicityly. 
      String s2 = "one";  // will be created in the String pool and interned automatically by the compiler.
    

    【讨论】:

    • "将在堆上创建"---也许。它也可以在堆栈上分配。这超出了程序员的控制范围。
    • @MarkoTopolnik - 请你说得更具体些。
    • 逃逸分析可以证明字符串可以安全地分配到栈中。
    • @MarkoTopolnik - 哦。从来不知道..谢谢:)
    【解决方案2】:

    String s1 = new String("one");在内存中新建一个字符串对象,而String s2 = "one";使用字符串池。

    在java中处理字符串时使用new关键字不是一个好习惯。

    【讨论】:

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