我有一个Employee,一个Organization和Test类。员工包含与Employee和Organization类相关的信息,包含Employee列表。请查看以下两个类的源代码:
Employee.java
package com.practice;
public class Employee {
private String empId;
private String name;
private int age;
private float salary;
public Employee(final String empId, final String name, final int age, final float salary) {
this.empId = empId;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getEmpId() {
return empId;
}
public void setEmpId(final String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(final float salary) {
this.salary = salary;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.empId + " " + this.name + " " + this.age + " " + this.salary;
}
}
Organization.java
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Organization {
private final List<Employee> empList = new ArrayList<Employee>();
Organization() {
}
public void addEmployee(final Employee emp) {
this.empList.add(emp);
}
public List<Employee> getEmpList() {
return empList;
}
}
TestGC.java
package com.practice;
public class TestGC {
public static void main(final String[] args) {
final Employee emp = new Employee("E1", "Emp 1", 20, 2000.0f);
final Employee emp2 = new Employee("E1", "Emp 1", 20, 2000.0f);
final Organization org = new Organization();
org.addEmployee(emp);
org.addEmployee(emp2);
System.out.println(org.getEmpList());
}
}
在Organization.java中,我们有Employee对象的列表,我在同一行创建了对象,这意味着在类级别。所以,我的问题是,一旦我完成了组织对象,该列表是否符合GC的条件,否则它将是内存泄漏?另外,如果我在构造函数中实例化相同的对象,它会有什么不同吗?
答案 0 :(得分:0)
您拥有的是常规实例变量(以及一些局部变量)。当它们不再可达时,它们将被正常收集。如果从构造函数中实例化它们没有区别,它只会添加不必要的代码。
答案 1 :(得分:0)
一旦我完成了组织,该列表是否符合GC的条件 对象或它会在内存中泄漏吗?
是。 organization
对象超出范围时,列表将有资格获得GC。您正在使用的只是实例变量,因此除非您使用一些静态变量,否则无需担心内存泄漏。
如果我在其中实例化相同的对象,它会有什么不同 构造
没有