[英]Linked List - Iterative add method - No getters and setters
您好,我有一個分配是在沒有getter和setter的適當類中創建一個迭代添加方法add(Student s),但是我可能會創建“輔助方法”(不確定其含義)和屬性。
我試圖使方法添加到Group類中:
public void add(Student s) {
if ( head == null) {
head = new Student(...);
// Struggling because Student constructor requires a String not a Student
}
}
我可以通過為該名稱創建一個吸氣劑來做到這一點,例如head = new Student(s.getName()); 但是我不允許使用getter和setter,該怎么辦? 謝謝
public class Student {
private final String name;
private int grade;
private Student next;
private static int counter = 0;
public Student(String name) {
this.name = name;
this.grade = 0;
}
}
public class Group {
private int groupnumber;
private Student head;
// Empty list & group number by default is 2
public Groupe() {
this.head = null;
this.groupnumber = 2;
}
}
您可以使用副本構造函數。 像新Student(student)
一樣。
public class Student {
private final String name;
private int grade;
private Student next;
private static int counter = 0;
public Student(Student template) {
this.name = template.name;
this.grade = template.grade;
}
}
或者,也許更簡單:
public void add(Student s) {
if ( head == null) {
head = s;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.