0

I have two classes, Class A and Class B.

Class A has an ArrayList of objects Class B.

Each Class B object has an attribute that stores a Class A object.

So when I create a Class A object, it populates the ArrayList of objects Class B. Each object Class B creates an object Class A (same as the one that is being populated), which creates an ArrayList of objects Class B... and so on.

What should I do to avoid this infinite recursion?

4

2 回答 2

1

This should fix infinite recursion: (Java assumed)

Class A {

  private ArrayList<B> list = new ArrayList<B>();
  A(){ 
    while(someCondition) {
      list.add(new B(this));
    }
  }
}

Class B {

  private A attribute;
  B(A inRef){ 
    attribute = inRef;
  }
}

Note that B's attribute field is not assigned using new but by passing in a reference to A. By not using new we do not create a new instance of the A class and avoid recursion.

于 2012-11-18T22:53:36.740 回答
0

I think, you misunderstand difference between class (as type) and object.

...So when I create a Class A object, it populates the ArrayList of objects Class B. Each object Class B creates an object Class A (same as the one that is being populated)... -- not exact same as object, but same as class. Each object B stores objects of class A. And once created object A is might not be the same object like A->B->A.

But if you want to have reference to parent object A from object B, you may use references (for example. you want to use its public methods and so on). So in this case you must not create new entities of object A in B, but, when you create your object B -- in constructor of B you must use as parameter reference to parent object A.

In C++ this trick is fairly common.

于 2012-11-18T23:04:25.497 回答