【问题标题】:I want to reference one object inside another that references the first object. What problems could this cause?我想在另一个引用第一个对象的对象中引用一个对象。这会导致什么问题?
【发布时间】:2017-09-24 17:34:08
【问题描述】:

我希望在访问课程时能够看到任何学生的班级,并且我还希望在访问班级时能够拥有学生列表。

例子:

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
    );

}}

这样编程有错吗?有没有更好的办法?

【问题讨论】:

    标签: java android redundancy


    【解决方案1】:

    不同类的对象相互交叉引用会产生循环依赖,应尽可能避免。

    创建循环依赖有很多缺点,比如编译时间长、模块化程度低、耦合度高等。

    【讨论】:

      【解决方案2】:

      唯一真正的负面因素是您需要保持数据同步 - 如果您从教室 A 中删除学生 1,您还需要从学生 1 中删除教室 A,否则您的数据不一致。

      我实际上建议使用第三个类来保持这些数据同步,因此一次调用是更改两个类的正确位置。如果你这样做,最好将关系存储在第二个班级,但将其存储在外部 - 例如,你可能决定最好为第三个班级的学生提供教室的 Multimap,而不是直接保存数据

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-25
        • 2013-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多