【问题标题】:About the keyword, "new" in Java [duplicate]关于Java中的关键字“new”[重复]
【发布时间】:2012-03-30 16:03:24
【问题描述】:

可能重复:
Questions about Java's String pool

各位大侠,这两者有什么区别。

(1)

String s = new String("hello"); // creating an object on heap then assign that object to the reference s.

(2)

String s = "hello" // did I make an object here?? Im not using the word new.

还有数组示例

int x[] = {1, 2, 3, 4, 5}; // did I make object here? 

【问题讨论】:

    标签: java


    【解决方案1】:

    String s = "hello"string literal“hello”分配给s

    使用new 关键字,除了字符串文字之外,您还可以创建一个新对象。

    注意:

    String s = "hello";
    System.out.println(s == "hello");
    s = new String("hello");
    System.out.println(s == "hello");
    

    很可能会成功

    true
    false
    

    由于s 引用字符串文字“hello” - 在第一种情况下你有一个身份,而在第二种情况下它是一个新对象,并且没有身份 - 这是两个不同的对象,碰巧包含相同的值。

    关于您的数组问题:是的,创建了一个 int[] 对象。

    【讨论】:

    • 请注意,字符串字面量是预定义字符串对象的源代码表示。因此,使用 new 关键字,您实际上是在制作现有 String 对象的 copy。所以你最终得到了 2 个 String 对象而不是一个。
    • 所以 String s = "hello" 没有创建新对象??我认为在 java 中一切都是对象??
    • @user1293258:它是一个对象,它只是一个字符串文字。 jvm 维护一个 pool 字符串文字,并重用相同的对象。因此,在 assiment s = "hello" 以及稍后将 s"hello" 进行比较时,使用了相同的字符串文字 - 这是同一个对象。关于:I thought in java everthing is an object - 这不是真的。 intboolean [和所有其他原始类型]是不是对象。
    • 这个怎么样?字符串 o = 新字符串(“你好”);那么 o == "hello" 答案将是错误的,为什么会因为字符串文字 "hello" 的最后一个字符为空字符?
    • @user1293258: new String("hello) 创建一个新对象。在 java 中,operator== 检查 identity 而不是 equality - 它检查两个对象是否是同一个对象 [“占用内存中的相同空间”]。 new String("hello") 位于内存中的一个新位置,而不是字符串文字之一,因此它们不是相同的对象,结果是 false 正如预期的那样。
    【解决方案2】:
    1. 是的,你已经创建了一个新的字符串 obj
    2. “你好”可能在堆中,但不是真的在堆中。它不是在运行时创建/分配的,而是在你的程序运行之前被实习。
    3. 是的,您在堆中创建了一个 int[]

    【讨论】:

      【解决方案3】:

      关于字符串构造函数,你总是有对象。

      当你说

      String test = "test";
      

      你创建了一个内容为“test”的字符串对象,但是当你说

      String test= new String("test");
      

      您创建一个内容为“test”的字符串对象并将其作为参数传递给字符串 构造函数来创建一个新的 String 对象。所以最后你有 创建了 2 个字符串对象。

      构造函数的代码是:

      public String(String original){.....}
      

      在大多数情况下,字符串构造函数被认为是无用的。

      在这个帖子中,他们描述了何时可以使用它

      Use of the String(String) constructor in Java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2013-06-28
        • 1970-01-01
        • 2012-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多