2012-06-25 34 views
4

我想了解Java。會發生什麼,我的ArrayList

讓我們假設我有一個大小爲50的ArrayList,並預先填入一些名稱。

讓我們假設我從數組列表中刪除第3個和第4個元素。我的數組列表會發生什麼?它會重新排列嗎?如果我嘗試訪問現在刪除的第三和第四個元素,它會返回null嗎?

回答

0

通常你用java collections爲動態存儲,而不定義大小。

List<String> list = new ArrayList<String>(); //dynamic 

對於靜態預定義集合,您使用java arrays

String[] array = new String[50]; //static 
+0

我不知道爲什麼這個帖子被標記爲回答,但我確實不認爲這個帖子回答了這個問題。以某種方式解釋ArrayLists是動態分配,簡單數組是靜態分配是正確的,但問題仍然要求不止於此。 –

18

不,你要刪除的那個元素後面的元素會移到左邊(昂貴的操作),所以你不會有任何漏洞。作爲備註:如果你刪除第三個元素,那麼第五個元素將被移動到左邊,所以如果之後你刪除第四個,那麼你將刪除第五個起始集合。要刪除兩個連續的元素,你應該提供兩次相同的索引。

2

陣列列表元素將被重新佈置

1

一個ArrayList是可以通過索引來引用的項目的連續列表。所以當你刪除一個項目時,所有下列項目都會被移動。

7

他們將被重新安排和移動。

如果您希望它們返回null,則只需將要刪除的元素設置爲空,而不是將其刪除即可。

1

元素將被移位。

參見ArrayList中的Javadoc刪除:

java.util.ArrayList 
public E remove(int index) 
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). 
Specified by: 
remove in interface List 
Overrides: 
remove in class AbstractList 
Parameters: 
index - the index of the element to be removed 
Returns: 
the element that was removed from the list 
Throws: 
IndexOutOfBoundsException - 
4

你爲什麼不自己嘗試一下?

List<String> list = new ArrayList<String>(); 
list.add("A"); 
list.add("B"); 
list.add("C"); 
list.add("D"); 
list.add("E"); 
list.add("F"); 
list.add("G"); 

for(int i = 0; i < list.size(); i++) System.out.println("index " + i + ": " + list.get(i)); 

System.out.println(); 
list.remove(0); // remove "A" 

for(int i = 0; i < list.size(); i++) System.out.println("index " + i + ": " + list.get(i)); 

OUTPUT:

index 0: A 
index 1: B 
index 2: C 
index 3: D 
index 4: E 
index 5: F 
index 6: G 

index 0: B 
index 1: C 
index 2: D 
index 3: E 
index 4: F 
index 5: G 
3

實際可用兩個選項:

final List<Character> x = new ArrayList<Character>(asList('a', 'b', 'c', 'd')); 
x.set(1, null); // removes an element without shifting 
x.remove(0); // removes an element with shifting 
System.out.println(x); 

打印

[null, c, d]