Java如何调用其他类的ArrayList并解决找不到方法的报错?
跨类调用ArrayList报错修复方案
问题根因
HumanResource类中的employeeList是构造方法内的局部变量,作用域仅限制在构造方法执行过程中,类下的GetemployeeList方法无法访问该变量,本身代码就无法正常编译。Employee类构造方法中,你尝试调用GetemployeeList方法的主体是String类型的入参employee,String类没有定义该方法,必然触发找不到方法的报错。
修复步骤
第一步:调整HumanResource类的变量作用域
将employeeList改为类的成员变量,保证getEmployeeList方法可以正常访问:
public class HumanResource { // 调整为成员变量 private FileReader file; private ArrayList<Employee> employeeList; public HumanResource(String fileName) { file = new FileReader(fileName); employeeList = new ArrayList<>(); for (int k = 0; k < file.getLines().size(); k++) { employeeList.add(new Employee(file.getLines().get(k))); } } public ArrayList<Employee> getEmployeeList() { return employeeList; } }
第二步:调整Employee类的调用逻辑
getEmployeeList是HumanResource类的成员方法,必须基于实例化完成的HumanResource对象才能调用,不能直接在构造阶段调用(此时HumanResource还在循环初始化员工列表,未完成实例化):
public class Employee { private String employee; private int employeeRank; private int employeeID; private int employeeExperience; private int employeeAge; private String employeeName; public Employee(String employeeInfo) { // 仅做自身属性的初始化,不要在这里调用人力资源列表 this.employee = employeeInfo; // 其余属性赋值逻辑自行补充 } // 单独定义方法获取全量员工列表,等HumanResource实例化完成后再调用 public ArrayList<Employee> getAllEmployee(HumanResource hr) { return hr.getEmployeeList(); } }
内容的提问来源于stack exchange,提问作者haris faizal
相关产品推荐
相关产品推荐

