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\n"+ myList); Collections.sort(myList); System.out.println("Points(升序)\n"+ myList); } }
输出结果
Points [50, 29, 35, 11, 78, 64, 89, 67] Points(升序) [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\n"+ myList); Collections.sort(myList); System.out.println("Points(升序)\n"+ myList); } }
输出结果
Points [50, 29, 35, 11, 78, 64, 89, 67] Points(升序) [11, 29, 35, 50, 64, 67, 78, 89]