2013-11-14 47 views
4

創建一個對象(o)的實例並將其添加到Arraylist(arrayList)工作正常。但是,刪除功能不起作用。ArrayList.add工作,但不是ArrayList.remove

arrayList.add(o); // works 
arrayList.remove(o); // does nothing 

我在想什麼?

+10

'o'類實現'equals'嗎?請參閱[這裏](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)) – Vidya

+1

請在一般情況下爲語言添加標籤提問。 – Rndm

+2

我們需要更多信息。 @Vidya說它應該實現平等,這是事實。另外,如果你使用整數,你可能會得到不正確的行爲;) –

回答

3

ArrayList.remove()這個樣子的:

public boolean remove(Object o) { 
    if (o == null) { 
     for (int index = 0; index < size; index++) 
      if (elementData[index] == null) { 
       fastRemove(index); 
       return true; 
      } 
    } else { 
     for (int index = 0; index < size; index++) 
      if (o.equals(elementData[index])) { 
       fastRemove(index); 
       return true; 
      } 
    } 
    return false; 
} 

因此,如果您Object有默認equals(),那麼這個斜面工作。所有對象都是不同的。將equals()添加到您的Object課程中。