2014-09-13 24 views
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"); 
    } 
} 
+0

還有就是「應該是」錯誤?這是一個功課問題嗎? – Ideasthete 2014-09-13 18:22:48

+1

'remove'中唯一的「泄漏」是在將最後一個項目複製到之前的項目之後,不會使最後一個數組元素無效。 – 2014-09-13 18:30:00

+0

歡迎來到Stack Overflow!這個問題看起來像我的功課。雖然問作業問題是完全沒問題的,但在這裏有一些很好的指導作業問題:[我如何問及回答作業問題?](http://meta.stackexchange.com/a/10812)。總結一下,他們是:先嚐試自己解決問題;讓我們知道問題在於作業;確保你的課程允許使用問答獲得幫助;不要先複製和粘貼答案的代碼,先不要理解它的作用和工作原理。 – 2014-09-14 02:04:42

回答

0

確保未使用items元素被設置爲從那裏不能被垃圾收集引用null否則對象。

後for循環減擋項目添加一行:

items[numItems-1] = null; 
+0

所以一旦一切都向下移動,最上面的索引仍然具有與之前相同的對象。我現在看到它,謝謝。 – Michael 2014-09-13 18:38:19