Java 删除方法中的内存泄漏在哪里?
我的代码中可能的内存泄漏在哪里?其中一个方法中也应该存在编程错误,如果我创建这个类的子类,可能会导致问题 add方法基本上只需要一个索引,来添加项目的位置。对于当前数组中索引之后占用任何内容的每个项,它只需将其复制到一个点上,然后将该项放入索引中。我看不出有什么问题 对于remove方法,它基本上做了相同的事情,只是做了相反的事情Java 删除方法中的内存泄漏在哪里?,java,arrays,memory-management,data-structures,memory-leaks,Java,Arrays,Memory Management,Data Structures,Memory Leaks,我的代码中可能的内存泄漏在哪里?其中一个方法中也应该存在编程错误,如果我创建这个类的子类,可能会导致问题 add方法基本上只需要一个索引,来添加项目的位置。对于当前数组中索引之后占用任何内容的每个项,它只需将其复制到一个点上,然后将该项放入索引中。我看不出有什么问题 对于remove方法,它基本上做了相同的事情,只是做了相反的事情 private static final int MAX_LIST = 3; protected Object []items; protected int nu
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");
}
}
private static final int MAX_LIST=3;
受保护对象[]项;
受保护的整数;
公共MyArray()
{
项目=新对象[最大列表];
numItems=0;
}
/*编程错误应该在这个方法中*/
公共空添加(整数索引,对象项)
抛出ListIndexOutOfBoundsException
{
if(numItems>items.length)
{
抛出新的ListException(“添加时的ListException”);
}
如果(索引>=0&&index=index;位置--)
{
项目[pos+1]=项目[pos];
}
项目[索引]=项目;
numItems++;
}
其他的
{
抛出新的ListIndexOutOfBoundsException(
“添加时的ListIndexOutOfBoundsException”);
}
}
/*内存泄漏应该在这个方法中*/
公共无效删除(整型索引)
抛出ListIndexOutOfBoundsException
{
如果(索引>=0&&index
确保未使用的项
元素设置为null
,否则从那里引用的对象不能被垃圾收集
在for循环下移后,添加一行项目:
items[numItems-1] = null;
“应该”有错误吗?这是一个家庭作业问题吗?
remove
中唯一的“漏洞”是在将最后一个项目复制到它前面的项目之后,没有将最后一个数组元素空值。欢迎使用堆栈溢出!这个问题对我来说像是家庭作业。虽然问家庭作业问题很好,但这里有一些关于问家庭作业问题的好指南:。概括起来,它们是:先尝试自己解决问题;让我们知道问题是家庭作业;确保你的班级允许使用问答获得帮助;在不了解答案的功能和工作原理的情况下,不要复制和粘贴答案的代码。因此,一旦所有内容都向下移动,最上面的索引仍然具有与以前相同的对象。我现在看到了,谢谢。