“我在這裡。”

“嗨,艾莉!”

“今天我們要聊一個有趣的話題,我要給大家講講ArrayList這個類。”

“一個新類?酷!它能做什麼?”

“讓我從背景說起。程序員唯一不喜歡數組的地方就是你不能改變它們的大小。如果你需要向一個只有一個空閒槽的數組添加三個以上的元素,你會怎麼做?

“解決這個問題的唯一方法是創建非常大的數組,以保證你有足夠的空間容納所有元素。然而,這通常意味著浪費內存。如果一個數組通常包含三個元素,但即使是最小的機會它可能需要容納 100 個元素,因此您必須創建一個包含 100 個元素的數組。”

“那麼,程序員想出了什麼?”

“他們編寫了ArrayList類,它做的事情與 Array 相同,但它可以改變它的大小。”

“有趣的舉動。他們是怎麼做到的?”

“每個ArrayList對像都存儲一個常規的元素數組。當您從 ArrayList 讀取元素時它會從其內部數組中讀取它們。當您將它們寫入 ArrayList 時它會將它們寫入其內部數組。在這裡,比較這些列:”

大批 數組列表
為元素創建容器
String[] list = new String[10];
ArrayList<String> list = new ArrayList<String>();
獲取元素個數
int n = list.length;
int n = list.size();
從數組/集合中獲取元素
String s = list[3];
String s = list.get(3);
將一個元素寫入數組
list[3] = s;
list.set(3, s);

“那麼,為什麼 ArrayList 更好?據我所知,代碼現在更長了。”

“首先,ArrayList支持程序員必須一直執行的幾個額外操作。普通數組不支持這些操作。例如,從數組中間插入或刪除元素而不留空洞。

“其次,改變數組大小的能力。當你需要添加一個元素但內部數組沒有任何空閒槽時,這是 ArrayList 內部發生的事情

a)創建另一個數組,它比當前內部數組大 50%,外加一個元素。

b)舊數組中的所有元素都被複製到新數組中。

c)新數組保存為 ArrayList 對象的內部數組。舊數組被聲明為垃圾(我們只是停止存儲對它的引用)。”

大批 數組列表
在數組末尾添加一個元素
不支持此操作
list.add(s);
在數組中間添加一個元素
不支持此操作
list.add(15, s);
在數組開頭添加一個元素
不支持此操作
list.add(0, s);
從數組中刪除一個元素
我們可以用刪除一個元素list[3] = null。但這會在數組中留下一個“洞”。
list.remove(3);
2
任務
Java Syntax,  等級 7課堂 5
上鎖
Code entry
Sometimes you don't need to think, you just need to hammer it out! As paradoxical as it may seem, sometimes your fingers will "remember" better than your conscious mind. That's why while training at the secret CodeGym center you will sometimes encounter tasks that require you to enter code. By entering code, you get used to the syntax and earn a little dark matter. What's more, you combat laziness.

“我們如何使用這個 ArrayList?”

“實際上,就像我們對普通數組所做的那樣。看。讓我們將使用 ArrayList 與使用數組進行比較。假設我們需要‘讀入 10 個字符串並以相反的順序將它們顯示在屏幕上’。”

“看這個:

用數組
public static void main(String[] args)
{
Reader r = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(r);

// Read strings from the keyboard
String[] list = new String[10];
for (int i = 0; i < list.length; i++)
{
  String s = reader.readLine();
  list[i] = s;
}

// Display the contents of the array
for (int i = 0; i < list.length; i++)
{
  int j = list.length - i - 1;
  System.out.println( list[j] );
}
}
使用 ArrayList
public static void main(String[] args)
{
Reader r = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(r);

// Read strings from the keyboard
ArrayList&ltString> list = new ArrayList&ltString>();
for (int i = 0; i < 10; i++)
{
  String s = reader.readLine();
  list.add(s);
}

// Display the contents of the collection
for (int i = 0; i < list.size(); i++)
{
  int j = list.size() - i - 1;
  System.out.println( list.get(j) );
}
}

我在每一欄中使用相同的顏色來突出顯示類似的操作。”

“一方面,一切都不一樣了。另一方面,還是一樣。”

“對。除了我們在使用ArrayList時不使用方括號。相反,我們使用getsetadd方法。”

“是的,我收集了這麼多。不過,它看起來非常相似。”