Java 简明教程
Java ArrayList Class
Introduction
Java ArrayList 类提供了 resizable-array 并实现了 List 接口。以下是关于 ArrayList 的重要要点 -
The Java ArrayList class provides resizable-array and implements the List interface.Following are the important points about ArrayList −
-
It implements all optional list operations and it also permits all elements, includes null.
-
It provides methods to manipulate the size of the array that is used internally to store the list.
-
The constant factor is low compared to that for the LinkedList implementation.
ArrayList 类扩展 AbstractList 并实现了 List 接口。ArrayList 支持可根据需要动态增长的数组。
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
标准 Java 数组是固定长度的。创建数组后,它们不能增长或缩小,这意味着你必须预先知道数组将容纳多少个元素。
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
数组列表创建时指定一个初始大小。当超过此大小时,集合将自动扩大。当移除对象时,数组可能会缩小。
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
Class declaration
以下是 java.util.ArrayList 的声明 −
Following is the declaration for java.util.ArrayList class −
public class ArrayList<E>
extends AbstractList<E>
implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
这里 <E> 表示一个元素。例如,如果你正在编译一个整数数组,则需要将其初始化为
Here <E> represents an Element. For example, if you’re building an array list of Integers then you’d initialize it as
ArrayList<Integer> list = new ArrayList<Integer>();
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractList
-
java.lang.AbstractCollection
-
java.util.Object
-
java.util.List
Adding, Removing Elements to ArrayList of Strings Example
以下程序演示了 ArrayList 支持的多种方法 -
The following program illustrates several of the methods supported by ArrayList −
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
这会产生以下结果 −
This will produce the following result −