在 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]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP