我有一个此类,用于从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
。
(我应该补充一点,HourlyEmployee
和MonthlyEmployee
都是扩展Employee
的类)
答案 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