“我從真正有用的開始怎麼樣?你現在會看到 ArrayList 和泛型可以使用的幾種方法:”
“示例 1:”
從鍵盤讀取數字列表
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in) );
ArrayList<Integer> list = new ArrayList<Integer>() ;
while (true)
{
String s = reader.readLine();
if (s.isEmpty()) break;
list.add(Integer.parseInt(s));
}
}
“示例 2:”
與上面相同,但偶數被添加到列表的末尾,奇數被添加到它的開頭。
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> list = new ArrayList<Integer>();
while (true)
{
String s = reader.readLine();
if (s.isEmpty()) break;
int x = Integer.parseInt(s);
if (x % 2 == 0) // Check that the remainder is zero when we divide by two
list.add(x); // Add to the end
else
list.add(0, x); // Add to the beginning
}
}
“示例 3:”
刪除所有大於 5 的數字:
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in) );
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(7);
list.add(11);
list.add(3);
list.add(15);
for (int i = 0; i < list.size(); ) // We moved the statement that increases i to inside the loop
{
if (list.get(i) > 5)
list.remove(i); // Don’t increase i if we deleted the current element
else
i++;
}
}
“示例 4:”
將一個數組分成兩部分——偶數和奇數
public static void main(String[] args) throws IOException
{
// Static initialization of the array
int[] data = {1, 5, 6, 11, 3, 15, 7, 8};
// Create a list where all elements are Integers
ArrayList<Integer> list = new ArrayList<Integer> ();
// Use the array to fill the list
for (int i = 0; i < data.length; i++) list.add(data[i]);
ArrayList<Integer> even = new ArrayList<Integer>(); // Even numbers
ArrayList<Integer> odd = new ArrayList<Integer>(); // Odd numbers
for (int i = 0; i < list.size(); i++)
{
Integer x = list.get(i);
if (x % 2 == 0) // If x is even
even.add(x); // Add x to the collection of even numbers
else
odd.add(x); // Add x to the collection of odd numbers
}
}
“示例 5:”
合併列表
public static void main(String[] args) throws IOException
{
ArrayList<Integer> list1 = new ArrayList<Integer>(); // Create a list
Collections.addAll(list1, 1, 5, 6, 11, 3, 15, 7, 8); // Fill the list
ArrayList<Integer> list2 = new ArrayList<Integer>();
Collections.addAll(list2, 1, 8, 6, 21, 53, 5, 67, 18);
ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(list1); // Add all values from each list to the new list
result.addAll(list2);
for (Integer x : result) // A fast way to loop over all elements, only for collections
{
System.out.println(x);
}
}
“太棒了!迭戈現在可以給我一卡車類似的練習嗎?”
“他會的。”
GO TO FULL VERSION