我希望在訪問任何學生時能夠看到課程,並且我還希望在訪問課程時能夠獲得學生名單。我想引用另一個引用第一個對象的對象。這會導致什麼問題?
例子:
public class ClassRoom {
public String nome;
public List<Student> students;
public ClassRoom(String nome){
this.nome=nome;
}}
和
public class Student {
public String nome;
public ClassRoom aClass;
public Student(String nome, ClassRoom aClass){
this.nome = nome;
this.aClass = aClass;
}}
和
public School(){
ClassRoom c1 = new ClassRoom("English 102");
Student s1 = new Student("Anna White", c1);
Student s2 = new Student("Beatrix Blue", c1);
Student s3 = new Student("Carlos Brown", c1);
Student s4 = new Student("Dayana Green", c1);
Student s5 = new Student("Elliot Red", c1);
Student s6 = new Student("Jefferson Pink", c1);
c1.students = new ArrayList<>();
c1.students.add(s1);
c1.students.add(s2);
c1.students.add(s3);
c1.students.add(s4);
c1.students.add(s5);
c1.students.add(s6);
//example
System.out.println(
c1.students.get(1).aClass.students.get(2).aClass.students.get(3).nome
);
}}
這是錯誤的這樣的計劃?有沒有更好的辦法?