如何通过实现聚合将对象添加到没有复制构造函数的数组中

时间:2017-04-22 23:24:34

标签: java arrays aggregate

我有类学生,我想通过聚合

将Student对象添加到类Application中的数组Student
public class Student {//Start class 

private String name; 
private int id; 
private double gpa; 


public Student(String name, int id, double gpa){  
this.name=name; 
this.id=id; 
this.gpa=gpa; 
}//End class 

由于我没有将Student对象作为参数的构造函数,因此我使用了Student类中已有的getter。 问题我的代码只适用于同情 如果你们能告诉我正确的方法来添加它而不制作新副本我会非常感激。

 public class Application {//Start class Application

    private Student[] studentList; 
    private int numOfStudent; 

    public Application (int size) {
    studentList= new Student[size]; }

    public void addStudent(Student s){
    if(numOfStudent<studentList.length){

    studentList[numOfStudent++]=new Student(s.getName(),s.getID(),s.getGpa()); } 
    }  
    }//End class  Application 

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题,你需要创建一个接受Student对象的构造函数。然后你将像这样设置变量:

public Student(Student s) {
this.name = s.getName();
this.id = s.getId();
this.gpa = s.getGpa();
}

答案 1 :(得分:0)

希望我能正确理解这个问题......当你在数组中添加它时,是否需要创建Student的新副本?

如果没有,你可以直接使用它,即

public void addStudent(Student s){
  if(numOfStudent<studentList.length){
    studentList[numOfstudents++] = s;
  }
}