我读过很多关于字符串实习的文章。
如果我创建一个String对象
方法一
String str= new String("test")
2 个对象在堆中创建,另一个在字符串池中创建。
如果方法一不执行则方法二
String str= new String("test").intern()
它将创建字符串 frpoom 堆到字符串池的副本。将创建多少个对象。我猜 3.一个将在堆中,另一个在池中和一个“测试”文字。
在这两种情况下,哪一个将符合 GC 的条件。我看到文章说正在创建 2,但我不明白为什么?
方法三
String s= new String("test")
String s1=s.intern()
除了 s 指向堆对象和 s1 指向池对象之外,它做同样的事情,它们都不符合 Gc 的条件。
我的理解正确吗???我对这个概念很困惑。
最佳答案
If I create a String object
String str= new String("test")
Objects are created one in heap and other in string pool.
一个字符串由两个对象组成,String
和 char[]
在某些版本的 Java 中它可能是一个 byte[]
或者实际上是 char[]
,后来被 byte[]
取代。这意味着可以创建 4 个,也许 5 个对象,除非字符串文字的字符串已经存在,在这种情况下,对于 Java 7 update 4+,它是 2 个,在此之前 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 之间的任何一个。所有这些都符合收集条件,除非它们在某处被强烈引用。
关于java - GC 字符串实习生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905598/