为每个实例化对象创建一个新的ArrayList

时间:2014-03-15 18:02:53

标签: java arraylist

我有一个班级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}}构造函数中。我是朝着正确的方向前进,还是我完全离开了?

感谢您的帮助!

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);
}