【问题标题】:Where is the memory leak in the remove method?remove方法中的内存泄漏在哪里?
【发布时间】: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


【解决方案1】:

确保将未使用的items 元素设置为null,否则从那里引用的对象无法被垃圾回收。

在 for 循环下移项目后添加一行:

items[numItems-1] = null;

【讨论】:

  • 因此,一旦所有内容都向下移动,最上面的索引仍然具有与之前相同的对象。我现在看到了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 2012-04-09
相关资源
最近更新 更多