在 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]

更新于: 2019-09-20

1K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.