GC 字符串实习生

String intern for GC

我读过很多关于字符串实习的文章。

如果我创建一个字符串对象

方法一

  String str= new String("test")

2 个对象在堆中创建,另一个在字符串池中创建。

如果方法一不执行则方法二

  String str= new String("test").intern() 

它将创建一个字符串 frpoom 堆的副本到字符串池。有多少个对象 created.I 猜测 3.One 将在堆中,其他在池中和一个 "test" 文字.

两个中哪个有资格获得 GC cases.I 看到文章说正在创建 2,但我不明白为什么?

方法三

    String s= new String("test")
    String s1=s.intern()

除了 s 指向堆对象和 s1 指向池对象并且 none 符合 Gc 条件外,它做同样的事情。

我的理解对吗???我对这个概念很困惑。

需要注意的地方是

  1. 对于 String 字面值自动进行实习,intern() 方法用于使用新的 String()

    [=32 构造的字符串=]
  2. Strings(更具体地说,字符串对象)如果变得不可访问,将被垃圾收集,就像任何其他 java 对象一样。

  3. String literals 通常不是垃圾收集的候选对象。对象将隐式引用该文字。

  4. point#3 的原因是如果在方法中使用文字来构建 String 只要方法可以执行就可以到达。

String intern() 方法:

最常用的字符串比较方法是equals()equalsIgnoreCase()方法。但是,这些方法可能需要大量内存来存储大量字符。 Java String intern() 方法帮助我们提高了两个String之间比较的性能。

intern() 方法,当应用于 String 对象时,returns 对该对象的引用(来自 Java 生成的字符串的哈希集),具有相同的内容作为原始对象。因此,如果代码对多个 String 对象使用 intern() 方法,那么我们的程序将使用更少的内存,因为它将在这些 String 之间的比较中重用对象的引用。

请记住,Java 会自动保留字符串文字。这意味着 intern() 方法将用于使用 new String().

构造的字符串

示例:

JavaStringIntern.java

package com.javacodegeeks.javabasics.string; 
public class JavaStringIntern { 
    public static void main(String[] args) { 

        String str1 = "JavaCodeGeeks"; 
        String str2 = "JavaCodeGeeks"; 
        String str3 = "JavaCodeGeeks".intern(); 
        String str4 = new String("JavaCodeGeeks"); 
        String str5 = new String("JavaCodeGeeks").intern(); 
        System.out.println("Are str1 and str2 the same: " + (str1 == str2)); 
        System.out.println("Are str1 and str3 the same: " + (str1 == str3)); 
        System.out.println("Are str1 and str4 the same: " + (str1 == str4)); //this should be "false" because str4 is not interned         
        System.out.println("Are str1 and str4.intern() the same: " + (str1 == str4.intern())); //this should be "true" now                 
        System.out.println("Are str1 and str5 the same: " + (str1 == str5)); 
    } 
} 

Output:
Are str1 and str2 the same: true
Are str1 and str3 the same: true
Are str1 and str4 the same: false
Are str1 and str4.intern() the same: true
Are str1 and str5 the same: true 

If I create a String object

 String str= new String("test")

Objects are created one in heap and other in string pool.

一个字符串由两个对象组成,Stringchar[] 在某些版本的 Java 中它可能是一个 byte[] 或者实际上是一个 char[] 后来被 byte[] 取代。这意味着可以创建 4 个,也许 5 个对象,除非字符串文字的字符串已经存在,在这种情况下它是 2 for Java 7 update 4+,在此之前 char[] 将被共享所以它可能是三个对象或只有 1 个。

String str= new String("test").intern() 

这完全相同,除了如果调用足够多,new String 可以分配到堆栈上,您可能会发现只创建了 char[]` 而不能将它放在堆栈上, 在这一刻。将来这也可能会被优化掉。

Which one will be eligible for GC in both cases.I have seen artilces that say 2 are getting created but i am unable to understand why?

根据情况,答案是 1 到 4 之间的任何一个。除非在某处被强烈引用,否则所有这些都符合收集条件。