[英]How to save data in ArrayList in Java?
I had a made method in Company class and calling it in PayrollApp class.我在Company类中有一个 made 方法并在PayrollApp类中调用它。 Firstly!首先! it works fine but whenever I call that method second time it throw indexoutofboundException .它工作正常,但每当我第二次调用该方法时,它都会抛出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 .问题是索引i
是Company
的静态变量,而ArrayList _employeeList
不是。
So the variable i
is shared by all instances of your object, whereas your ArrayList _employeeList
is an instance variable.所以变量i
被你的对象的所有实例共享,而你的 ArrayList _employeeList
是一个实例变量。
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.所以当你第一次做company.setAddEmployee()
,它工作正常,因为 arrayList 和 i 都是空的,所以它可以工作,并且 i 增加到 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.但是下次当您为不同的company
对象执行company.setAddEmployee()
,该对象的 arrayList 为空,但 i 为1
因为变量i
是静态的,并由Company
类的所有实例 (Object) 共享。
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.要么你需要让ArrayList
静态的,要么你需要让i
非静态(成员变量),尽管你甚至可能不需要i
(我们也可以做_employeeList.add(<element>)
,它会在下一个可用索引),但我无法评论您如何解决该问题,因为我不确定您要使用代码实现什么目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.