我很好奇如何删除字符串池中的值?
假设:
String a = "ABC"; // has a reference of string-pool
String b = new String("ABC"); // has a heap reference
b = null;
a = null;
Run Code Online (Sandbox Code Playgroud)
在GC的情况下,来自堆的"ABC"被收集但"ABC"仍然在池中(因为它在permGen和GC中不会影响它).
如果我们继续添加如下值:
String c = "ABC"; // pointing to 'ABC' in the pool.
for(int i=0; i< 10000; i++) {
c = ""+i;
// each iteration adds a new value in the pool. Previous values don't have a pointer.
}
Run Code Online (Sandbox Code Playgroud)
我想知道的是:
作为此代码的一部分
String c = "ABC"; // pointing to 'ABC' in pool.
for(int i=0; i< 10000; i++) {
c = ""+i; // each iteration add new value in pool. and pervious values has no pointer
}
Run Code Online (Sandbox Code Playgroud)
String
池中只有两个对象,这两个对象来自两个String
文字"ABC"
和""
。String
从串联创建的每个其他对象都将是具有常规 GC 行为的常规对象,即。当它们不再可达时进行收集的候选者。
String
来自String
池中文字的值将不会被收集,因为它们始终是可访问的(带有类加载器的 YMMV)。String
被保留但不是来自文字的对象应该以常规方式成为 GC 的候选者。
更多值得阅读的内容: