垃圾回收(Garbage Collection)是一种自动管理内存的机制,在编程语言中,它负责自动检测和释放不再被程序使用的内存,以避免内存泄漏和内存碎片的问题。
以下是一段示例代码:
public class Example {public static void main(String[] args) {// 创建一个对象Person person = new Person("John", 25);// 输出对象的信息System.out.println(person.toString());// 将对象置为空,使其成为垃圾person = null;// 手动请求垃圾回收System.gc();// 输出对象的信息,预期应该为 nullSystem.out.println(person.toString());}
}class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}@Overrideprotected void finalize() throws Throwable {super.finalize();System.out.println("Person object is garbage collected");}
}
注释如下:
public class Example {public static void main(String[] args) {// 创建一个对象Person person = new Person("John", 25);// 输出对象的信息System.out.println(person.toString());// 将对象置为空,使其成为垃圾person = null;// 手动请求垃圾回收System.gc();// 输出对象的信息,预期应该为 nullSystem.out.println(person.toString());}
}
class Person {private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}@Overrideprotected void finalize() throws Throwable {super.finalize();System.out.println("Person object is garbage collected");}
}
public class Example:定义了一个公共的类Example。public static void main(String[] args):主函数,程序的入口点。Person person = new Person("John", 25);:创建一个Person类的对象person,传入参数 "John" 和 25。System.out.println(person.toString());:调用person对象的toString()方法并打印返回的字符串。person = null;:将person对象的引用置为null,这样它不再被引用,成为了垃圾。System.gc();:手动请求垃圾回收。System.out.println(person.toString());:尝试调用person对象的toString()方法并打印返回的字符串,预期结果应为null。class Person:定义了一个名为Person的类。private String name;和private int age;:定义了Person类的私有属性name和age。public Person(String name, int age):Person类的构造函数,用于初始化对象的属性。public String toString():重写了Object类的toString()方法,返回一个字符串表示Person对象的信息。protected void finalize() throws Throwable:重写了Object类的finalize()方法,当对象被垃圾回收时会调用该方法,这里添加了一个打印语句,用于确认对象是否被回收。