比如有student类和card(学生证)类,两者都定义持有对方的一个引用。class Student{
private int id;
private int age;
private String name;private Card card;
...
}
class Card{
private int cardid;
private String name;
private String stu_id;
private Student stu;
...
}
假定有get和set方法了。那么这种情况,实际的对象里面不是一个有另一个,而另一个有指向它,如此不是循环没完了吗?晕了,想想都头疼,请问这里面是怎么构造的,实际的对象里面又有什么?它们的垃圾回收又怎么回事? 这种情况有的,比如Hibernate 里面的一对一双向关联映射。

解决方案 »

  1.   

    垃圾回收一般不采用引用计数的方式,而采用root set的方法,所以这种问题,不算是问题。
      

  2.   


    不懂!   我被互相持有弄晕了,一个student对象里有card,而card对象里有student,......反反复复,到底这对象里面有什么啊,或者谁帮我画个内存状态图理解一下?高手别吝赐教啊,谢谢了。
      

  3.   

    ???你是说:引用是一个内存的地址,而对象实际占一块内存吗?比如以student开始,先new一个card对象,那么,这个card对象的内存地址放在随后new出的student对象中,那么那个card对象里面的student引用放的什么???好像先有鸡还是先有蛋啊?   
      

  4.   


    不用管这么多,其实就是hibernate中的一对一双向外键关联.你完全可以去掉一个外键用@OneToOne(mappedBy="")注解
    还不懂我可以看看我博客http://hi.baidu.com/martian_ma/blog/item/17fd552ba1d3b5335243c12e.html
    我也刚学, 一对一双向外键关联和生成的表无关,只是从表到对象是双向的而已.
      

  5.   

    我感觉这个像手里拿一面镜子,再对着一面镜子的。镜子里面有镜子。谁能告诉我java是怎么处理的啊?
      

  6.   

    class Student{
    public setCard(Card card){
         this.card=card;
    }
    private Card card;
    ...
    }
    class Card{
    public setStu(Student stu){
         this.stu=stu;
    }
    private Student stu;
    ...
    }
    main:
    {
          Card c= new Card();
          Student s=new Student();
          c.setStu(s);
          s.setCard(c);
    }
      

  7.   

    你错了,我查了下网上,这种情况叫循环引用(cycle reference),比较麻烦的问题,有的语言里这种引用会引起堆栈溢出;不知道java怎么处理的,好像都继承一个特别的接口就解决了;而且java的垃圾回收机制处理这种循环引用,自引用比别的语言要好。唔,这好像不是我现阶段需要了解的知识,无意中发现了,继续学习就好了。谁介绍一下就更好了。
      

  8.   

    关于GC,可以看我blog,写得内容比较综合。当科普了。
    http://www.cnblogs.com/healerkx/category/171828.htmlIE6和IE7,当有循环引用的时候,js就可能泄露,而firefox就不会不过真实的Java,C#的gc的泄露,不是机制问题,是逻辑问题。
      

  9.   

    是的,这叫循环引用。不过并不影响GC的判断,只要对象变为不可达就会被GC回收。这是关于可达性的解说:Reachability
    Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows: 
    An object is strongly reachable if it can be reached by some thread without traversing any reference objects. A newly-created object is strongly reachable by the thread that created it. 
    An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference. 
    An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization. 
    An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it. 
    Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.来自http://java.sun.com/javase/6/docs/api/java/lang/ref/package-summary.html#reachability