简体   繁体   中英

How to save data in ArrayList in Java?

I had a made method in Company class and calling it in PayrollApp class. Firstly! it works fine but whenever I call that method second time it throw indexoutofboundException . I am running this app on console without using database. I want to add all employees object into that arraylist.

public class Company {
    private ArrayList<Employee> _employeeList = new ArrayList<Employee>();
    public void setAddEmployee(Employee c){
        _employeeList.add(c);
    }
}

Employee emp = new Employee(_name, _empId);
emp.setNumOfHoursPerWeek(_hoursPerWeek);
emp.setHourlySalary(_hourlySalary);
emp.setManagerName(_manager);
Company com = new Company();

com.setAddEmployee(emp);

The issue is that the index i is a static variable of Company whereas ArrayList _employeeList is not .

So the variable i is shared by all instances of your object, whereas your ArrayList _employeeList is an instance variable.

So the first time you do company.setAddEmployee() , it works fine, because both arrayList is empty as well as i is 0, so it works, and i is incremented to 1.

but next time when you do company.setAddEmployee() for a different company object, the arrayList for that object is empty, but i is 1 as the variable i is static and shared by all instances (Object) of Company class.

Either you need to make the ArrayList static as well, or you need to make i non-static (member variable) , though you may not even need i (We can also do _employeeList.add(<element>) and it will add at the next available index) , But I cannot comment on how you can fix the issue, since I am not sure what you are trying to achieve with the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM