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