【发布时间】:2014-09-13 18:11:58
【问题描述】:
我的代码中可能的内存泄漏在哪里?在其中一个方法中也应该存在编程错误,如果我创建此类的子类可能会导致问题。
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");
}
}
【问题讨论】:
-
存在“应该是”错误?这是作业题吗?
-
remove中唯一的“泄漏”是,在将最后一项复制到它之前的一项之后,您不会将最后一个数组元素清空。 -
欢迎来到 Stack Overflow!这个问题对我来说就像家庭作业。虽然问家庭作业问题很好,但这里有一些很好的指导家庭作业问题:How do I ask and answer homework questions?。概括起来就是:先尝试自己解决问题;让我们知道问题是家庭作业;确保您的班级允许使用问答来寻求帮助;在不了解答案的作用和工作原理之前,不要复制和粘贴答案的代码。
标签: java arrays memory-management data-structures memory-leaks