【发布时间】:2014-07-05 07:12:57
【问题描述】:
我很难创建一种方法来递归删除对具有以下类的对象的所有引用:
class CoolObject
{
int someData;
CoolObject[] subObjects; // array and each element get initialized elsewhere
void nullSubObjects()
{
if(subObjects != null)
{
for (int o = 0; o < subObjects.length; o++)
{
if (subObject[o] != null)
{
subObject[o].nullSubObjects(); //returns exception here
subObject[o] = null;
}
}
subObjects = null;
}
}
}
Class elsewhere
{
void update(CoolObject currentObject)
{
//test for creation
if(currentObject.subObject == null && and other conditions)
{
currentObject.subObject = new CoolObject[52];
for(int m = 0; m < 52; m++)
currentObject.subObject[m] = new CoolObject();
}
//test for deletion
if(currentObject.subObject != null && and other conditions)
currentObject.nullSubObjects();
//recursive update
if(currentObject.subObjects != null)
for (int q = 0; q < 52; q++) update(currentObject);
}
}
每当我去更新结构时,它都会导致循环内出现空指针异常,尽管刚刚检查过以确保子对象不为空...
为什么会出现此异常?
如果不明确取消它,'someData' 会阻止它们的 GC 吗?
感谢大家的反馈!
这个实现是确保子对象更有可能被自动 GC 删除的一种过于复杂的方法。我已经决定在更高级别取消 subObjects 数组,并调用 System.gc()
如果不这样做,我原本 40k 的程序将在删除任何内容之前超过 2Gb。
【问题讨论】:
-
修复它的方法是读取 NullPointerException 的堆栈跟踪以了解它被抛出的位置,从而了解什么是 null。
-
除此之外,这是一种非常糟糕的代码格式化方式...非常不清楚。
-
您的问题实际上是关于是否需要将所有内容设置为 null(您几乎可以肯定不需要)或为什么会出现异常?
-
数组和每个元素都在别处初始化你能提供那个代码吗??
-
您清楚地向我们展示了编写的代码,而不是向我们展示了实际代码。而且您还没有发布异常的堆栈跟踪。投票结束。