如何制作将数组添加到arraylist并对其调用方法的main方法?

时间:2018-12-05 14:33:19

标签: java arraylist main

我有一个此类,用于从double内的数组中提取类型为ArrayList的值,并按定义的速率增加它们:

import java.util.ArrayList;

public class Company {
    static ArrayList<Employee> employees;

    public Company() {
        Company.employees = new ArrayList<Employee>();
    }


    public static ArrayList<Employee> getEmployees() {
        return employees;
    }

    public static void setEmployees(ArrayList<Employee> employees) {
        Company.employees = employees;
    }

    public void increaseSalaries(double rate) {
        if (rate <= 0.0) {
            throw new IllegalArgumentException();
        } else {
            for (int i = 0 ; i < employees.size() ; i++) {
                employees.get(i).increaseSalaries(rate);
            }
        }
    }
}

我想写一个主要的方法来建立一个arraylist并在其上调用该方法,但是我不确定如何。到目前为止,我有

public static void main(String[] args) {
    Company businesstown;
    HourlyEmployee george;
    MonthlyEmployee ambrose;
    george = new HourlyEmployee("George", "McClellan", "1537", 1.04);
    ambrose = new MonthlyEmployee("Ambrose", "Burnside", "1536", 741.0);
}

但是我不确定如何将这些数组添加到ArrayList商业区。我已经尝试了.add(george);的许多组合,但是我做对了。要么说

  

未为公司类型定义方法add(HourlyEmployee)

或者它编译并抛出一个NullPointerException

(我应该补充一点,HourlyEmployeeMonthlyEmployee都是扩展Employee的类)

2 个答案:

答案 0 :(得分:1)

我认为最好将ArrayList设置为类的私有成员,并具有添加员工的add方法

public class Company {
    private ArrayList<Employee> employees;

    public Company() {
        employees = new ArrayList<Employee>();
    }

    public void addEmployee(Employee e) {
        employees.add(e);
    }
    //rest of code
}

和主要

public static void main(String[] args) {
    Company businesstown = new Company();
    HourlyEmployee george = new HourlyEmployee("George", "McClellan", "1537", 1.04);
    MonthlyEmployee ambrose = new MonthlyEmployee("Ambrose", "Burnside", "1536", 741.0);
    businesstown.add(george);
    businesstown.add(ambrose);
}

答案 1 :(得分:0)

您可以将它们添加到返回的getEmployees的{​​{1}}中:

List

但是请确保在访问businesstown.getEmployees().add(george); businesstown.getEmployees().add(ambrose); 之前初始化实例及其中的employees

businesstown