在Java中将对象添加到固定集合(Array)中的方法

我创建了一个inheritance层次结构,其中包含一个名为Employe的超类和两个名为Lecturer和Assistant的子类。 除此之外,我还创建了一个名为Subject的类,它有一系列员工。

我想在这里做的是创建一个方法,将Employe对象添加到数组中。
我做了同样适用于ArrayList的那个,但它似乎不适用于Arrays。

如果可能的话,我怎样才能创建一个与数组做同样事情的方法?

public class Subject { private String subjectcode; private Employe[] employees; public Subject(String subjectcode) { this.subjectcode = subjectcode; Employe[] employees = new Employe[5]; } public void setSubjectcode(String code) { this.subjectcode = code; } public String getSubjectcode() { return this.subjectcode; } public boolean addStaff(Employe employe) { if (employe instanceof Lecturer || employe instanceof Assistant) { this.employees.add(employe); return true; } else { return false; } } } 

您需要使用ArrayList:

 public class Subject { private String subjectcode; private final List employees = new ArrayList(); public Subject(String subjectcode){ this.subjectcode = subjectcode; } public boolean addStaff(Employe employe){ return this.employees.add(employe); } 

或者,如果您仍想使用数组:

 public boolean addStaff(Employe employe){ List tempList = Arrays.asList(this.employees); boolean added = tempList.add(employe); this.employees = tempList.toArray(this.employees); return added; } 

数组不能像ArrayList一样动态增长或缩小,这就是为什么没有add()方法 – 它在数组实例已满后就停止工作了。

你对数组所拥有的基本上是get(index)set(index, value) ,所以当你知道你将拥有最多N雇员时, Subject可能如下所示:

 public class Subject { private static final int N = 5; private String subjectcode; private Employe[] employees = new Employe[N]; private int size = 0; public Subject(String subjectcode){ this.subjectcode = subjectcode; } public void setSubjectcode(String code){ this.subjectcode = code; } public String getSubjectcode(){ return this.subjectcode; } public boolean addStaff(Employe employe){ if (size == employees.length) { // cannot add when is full return false; } if(employe instanceof Lecturer || employe instanceof Assistant){ this.employees[size++] = employe; return true; } return false; } } 

另一方面,如果您不知道Subject在创建Subject时有多少员工(如果您知道它,您可以将N作为构造函数参数传递),那么您必须实现方法增加内部数组并在添加新员工时调用它,这可能如下所示:

 private void ensureCapacity(int n) { int oldCapacity = employees.length; if (oldCapacity >= n) { // there's nothing to do return; } // grow at least in half, to minimize copying data on each add int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - n < 0) newCapacity = n; employees = Arrays.copyOf(employees, newCapacity); } public boolean addStaff(Employe employe) { ensureCapacity(size + 1); if (employe instanceof Lecturer || employe instanceof Assistant) { this.employees[size++] = employe; return true; } return false; } 

有关增长数组的更好示例,请参阅JDK中ArrayListensureCapacity(int minCapacity) 默认实现 。

但同样,这种不断增长的东西只是重新实现了ArrayList已有的function。

对于Java数组,与ArrayList不同,您没有add方法。 所以,你不能添加它。 数组操作如下:

  String[] employees = new String[5]; employees[0] = "ad"; 

因此,数组需要基于索引的方法,其中指定在索引0处放置此元素,在索引1处放置此元素,依此类推…. employees[0] = "as";

在你的情况下,为什么你需要使用数组? 根据您提供的信息,我认为ArrayList最合适。