2014-02-12 58 views
-1

當我刪除arraylist中的某些中間元素時會發生什麼?它會自動重新排列整個數組列表嗎?例如,考慮下面的情況下迭代arraylist並在java中刪除

list.add(one); /** has index 0 ***/ 
list.add(two); /** has index 1 ***/ 
list.add(three); /** has index 2 ***/ 

如果刪除具有索引1處的第二元件,那麼什麼是具有「三」的對象的索引。是ArrayList自動重新排列,整個列表及其索引,當數組列表的大小很大?

+4

就試一下,並找出,沒有昂貴? – 2014-02-12 06:19:51

+0

簡短的回答是「是」...但你應該運行你自己的測試看看。 – MadProgrammer

+1

在我的情況下是數組列表非常大。和謝謝你 – Strawberry

回答

1

JLS

Removes the element at the specified position in this list. 
Shifts any subsequent elements to the left (subtracts one from their indices). 
0

從該ArrayList

public E remove(int index) { 
    RangeCheck(index); 

    modCount++; 
    E oldValue = elementData[index]; 

    int numMoved = size - index - 1; 
    if (numMoved > 0) 
     System.arraycopy(elementData, index+1, elementData, index, 
       numMoved); 
    elementData[--size] = null; // Let gc do its work 

    return oldValue; 
    } 

的源可以看出其創建一個副本。因此,如果你使用的索引操作修改一個ArrayList是索引將被更新

0

,ArrayList的將重新排列,因爲你已經瞭解。這就是爲什麼的ArrayList是,如果有太多的修改

這就是刪除(INT)的文件說

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).