0
我的代码中可能的内存泄漏在哪里?在一个方法中也会出现编程错误,如果我创建了这个类的子类,可能会导致问题。删除方法中的内存泄漏在哪里?
add方法基本上只需要索引添加项目的位置。对于每个在当前数组中的索引之后占据任何内容的项目,它只是将它复制到一个点上,然后将项目放入索引中。我没有看到它有什么问题。
对于remove方法,它基本上做了同样的事情,除了相反。
private static final int MAX_LIST = 3;
protected Object []items;
protected int numItems;
public MyArray()
{
items = new Object[MAX_LIST];
numItems = 0;
}
/*the programming error should be in this method*/
public void add(int index, Object item)
throws ListIndexOutOfBoundsException
{
if (numItems > items.length)
{
throw new ListException("ListException on add");
}
if (index >= 0 && index <= numItems)
{
for (int pos = numItems-1; pos >= index; pos--)
{
items[pos+1] = items[pos];
}
items[index] = item;
numItems++;
}
else
{
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on add");
}
}
/*The memory leak should be in this method*/
public void remove(int index)
throws ListIndexOutOfBoundsException
{
if (index >= 0 && index < numItems)
{
for (int pos = index+1; pos < numItems; pos++)
{
items[pos-1] = items[pos];
}
numItems--;
}
else
{
throw new ListIndexOutOfBoundsException(
"ListIndexOutOfBoundsException on remove");
}
}
还有就是“应该是”错误?这是一个功课问题吗? – Ideasthete 2014-09-13 18:22:48
'remove'中唯一的“泄漏”是在将最后一个项目复制到之前的项目之后,不会使最后一个数组元素无效。 – 2014-09-13 18:30:00
欢迎来到Stack Overflow!这个问题看起来像我的功课。虽然问作业问题是完全没问题的,但在这里有一些很好的指导作业问题:[我如何问及回答作业问题?](http://meta.stackexchange.com/a/10812)。总结一下,他们是:先尝试自己解决问题;让我们知道问题在于作业;确保你的课程允许使用问答获得帮助;不要先复制和粘贴答案的代码,先不要理解它的作用和工作原理。 – 2014-09-14 02:04:42