
销毁未引用对象的过程称为垃圾收集(GC)。一旦某个对象未被引用,它就会被视为未使用的对象,因此JVM会自动销毁该对象。
有多种方法可以使对象符合 GC 的条件。
通过取消对对象的引用
一旦达到创建对象的目的,我们就可以将所有可用的对象引用设置为“null”。
示例
public class GCTest1 {
public static void main(String [] args){
String str = "Welcome to TutorialsPoint"; // String object referenced by variable str and it is not eligible for GC yet.
str = null; // String object referenced by variable str is eligible for GC.
System.out.println("str eligible for GC: " + str);
}
}输出
str eligible for GC: null
通过将引用变量重新分配给其他对象
我们可以使引用变量引用另一个对象。将引用变量与对象解耦,并将其设置为引用另一个对象,因此重新分配之前引用的对象有资格进行GC。
立即学习“Java免费学习笔记(深入)”;
示例
public class GCTest2 {
public static void main(String [] args){
String str1 = "Welcome to TutorialsPoint";
String str2 = "Welcome to Tutorix"; // String object referenced by variable str1 and str2 and is not eligible for GC yet.
str1 = str2; // String object referenced by variable str1 is eligible for GC.
System.out.println("str1: " + str1);
}
}输出
str1: Welcome to Tutorix











