什么是对象间的循环引用和自身引用?
如题
请举例说明。。。谢谢~~
------解决方案--------------------循环引用和
class A
{
A p;
}
A a=new A();
a.p=new A();
a.p.p=a;
自身引用
A a=new A();
a.p=a;
------解决方案--------------------循环引用:A用了B,B用了A
class A
{
private B b;
}
class B
{
private A a;
}
自身引用
class A
{
private A a;
}
有点像是死循环,但是由于存的是引用,只要不发生类似于:
class A
{
private A a = new A();
}
的代码应该就没事吧
------解决方案--------------------这两种引用是不是会导致实例不会被垃圾处理程序回收
------解决方案--------------------是不是低归啊 ??
我饿不明白啊 !!!
------解决方案--------------------循环引用就像malligator(只在此山中) 说得:
A用了B,B用了A
class A
{
private B b;
}
class B
{
private A a;
}
这种方式会不会导致不被垃圾回收器回收要看垃圾回收器采用的算法.
采用 "火车算法 "的垃圾回收机制就可以处理这种循环引用的问题.
关于自身引用,是static的时候才有意义吧.
比如构造一个枚举类.
thinking in java上的代码:
public final class Month {
private String name;
private Month(String nm) { name = nm; }
public String toString() { return name; }
public static final Month
JAN = new Month( "January "),
FEB = new Month( "February "),
MAR = new Month( "March "),
APR = new Month( "April "),
MAY = new Month( "May "),
JUN = new Month( "June "),
JUL = new Month( "July "),
AUG = new Month( "August "),
SEP = new Month( "September "),
OCT = new Month( "October "),
NOV = new Month( "November "),
DEC = new Month( "December ");
public static final Month[] month = {
JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC
};
public static final Month number(int ord) {
return month[ord - 1];
}
public static void main(String[] args) {
Month m = Month.JAN;
System.out.println(m);
m = Month.number(12);
System.out.println(m);
System.out.println(m == Month.DEC);
System.out.println(m.equals(Month.DEC));
System.out.println(Month.month[3]);
}
}