在 Java 中初始化 ArrayList
ArrayList 類擴充套件了 AbstractList,並實現了 List 介面。ArrayList 支援可以根據需要動態增長的陣列。陣列列表以初始大小建立。當超過此大小時,集合會自動擴大。當刪除物件時,陣列可能會縮小。
現在,讓我們看看如何使用 add() 方法初始化 ArrayList −
示例
import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(); myList.add(50); myList.add(29); myList.add(35); myList.add(11); myList.add(78); myList.add(64); myList.add(89); myList.add(67); System.out.println("Points
"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)
"+ myList); } }
輸出
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending) [11, 29, 35, 50, 64, 67, 78, 89]
現在,讓我們看看使用 asList() 方法初始化 ArrayList 的另一種方法 −
示例
import java.util.*; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(Arrays.asList(50,29,35,11,78,64,89,67)); System.out.println("Points
"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)
"+ myList); } }
輸出
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending order) [11, 29, 35, 50, 64, 67, 78, 89]
廣告