目前我有這樣的代碼:對象的防守副本添加到HashSet
public final class Tutor {
private String name;
private final Set<Student> tutees;
public Tutor(String name, Student[] students){
this.name = name;
tutees = new HashSet<Student>();
for (int i = 0; i<students.length; i++)
tutees.add(students[i]);
}
我試圖這樣,它使/添加,而不是學生的防守副本重寫它(只是紙上談兵)直接將它們添加到HashSet的,我想知道,如果下面的代碼將這樣做:如果需要的學生
public final class Tutor {
private String name;
private final Set<Student> tutees;
public Tutor(String name, Student[] students){
this.name = name;
tutees = new HashSet<Student>();
for (int i = 0; i<students.length; i++)
tutees.add(students[i](students.getName(), students.getCourse());
}
代碼:
public class Student {
private String name;
private String course;
public Student(String name, String course){
this.name = name;
this.course = course;
}
public String getName() { return name; }
public String getCourse() { return course; }
public void setName(String name) {
this.name = name;
}
public void setCourse(String course){
this.course = course;
}
}
謝謝
首先使用編譯器。它會發現至少一個錯誤。接下來,請考慮爲學生編寫一個構造函數,將Student作爲參數 - 封裝在Student類中複製學生需要的內容。 –