我有一个班级Employee
,如下所示:
import java.util.ArrayList;
public class Employee extends Person
{
int salary;
ArrayList<Sales> sales = new ArrayList<>();
public Employee(String name, int phoneNumber, String address,
int salary, ArrayList<Sales> sales)
{
super(name, phoneNumber, address);
this.salary = salary;
this.sales = sales;
}
}
现在,对于每个Employee
,我还必须存储ArrayList
每个Employee
的销售额Sales
。我的方法是创建一个ArrayList<Sales> sales = new ArrayList<>();
类并将Employee
添加到{{1}}构造函数中。我是朝着正确的方向前进,还是我完全离开了?
感谢您的帮助!
答案 0 :(得分:0)
首先,您应该使用字段的List
接口来促进松散耦合!其次,List
包含您应该用来复制列表元素的addAll
方法:
// ...
private int salary;
private List<Sales> sales = new ArrayList<>();
public Employee(String name, int phoneNumber, String address, int salary, List<Sales> sales) {
super(name, phoneNumber, address);
this.salary = salary;
this.sales.addAll(sales);
}