日期:2014-05-20  浏览次数:20761 次

下面有段代码不明白,请教一下
class   Garbage
{
int   index;
static   int   count;
Garbage()
{
count++;
System.out.println( "object   "+count+ "   construct ");
setID(count);
}

void   setID(int   id)
{
index=id;
}

protected   void   finalize()
{
System.out.println( "object   "+index+ "   is   reclaimed ");
}

public   static   void   main(String[]   args)
{
new   Garbage();
new   Garbage();
new   Garbage();
new   Garbage();
System.gc();
}
}


当程序执行的时候结果如下:

object   1   construct
object   2   construct
object   3   construct
object   4   construct
object   4   is   reclaimed
object   3   is   reclaimed
object   2   is   reclaimed
object   1   is   reclaimed

但我认为结果应该是:

object   1   construct
object   2   construct
object   3   construct
object   4   construct
object   4   is   reclaimed
object   4   is   reclaimed
object   4   is   reclaimed
object   4   is   reclaimed

index的值为什么会减少呢???不明白,请指教....

------解决方案--------------------
晕,index又不是static变量,四个不同的Garbage实例里面的index都不一样的啊
------解决方案--------------------
void setID(int id)
{
index=id;
}

这句index把每个ID都记录了下来