- import java.util.ArrayList;
- import java.util.List;
- abstract class Root{
- private List<Object> incomingReferenceList = new ArrayList<Object>();
-
- public void addIncomingReferenceObject(Object obj){
- if(!incomingReferenceList.contains(obj))
- incomingReferenceList.add(obj);
- }
-
- public int getReferencedCount(){
- return incomingReferenceList.size();
- }
- }
- class A extends Root{
- private B b;
-
- public void setB(B b){
- this.b = b;
- b.addIncomingReferenceObject(this);
- }
- }
- class B extends Root{
- private A a;
-
- public void setA(A a){
- this.a = a;
- a.addIncomingReferenceObject(this);
- }
- }
复制代码 维护一个反向引用列表就行了 |