ArrayList
类是 Java 集合框架中的一种实现,提供了动态数组的能力,可以根据需要自动扩容或缩小。通过 ArrayList
类,我们可以更方便地进行数组相关操作。
下面是 Java 中 ArrayList
类的一个简单示例:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
// 初始化一个 ArrayList 对象
ArrayList<String> list = new ArrayList<>();
// 添加元素
list.add("apple");
list.add("banana");
list.add("orange");
// 获取列表长度
System.out.println("The size of the list is: " + list.size());
// 访问元素
System.out.println("The first element of the list is: " + list.get(0));
// 修改元素
list.set(0, "pear");
System.out.println("Now the first element of the list is: " + list.get(0));
// 删除元素
list.remove(2);
System.out.println("After removing the third element, the list is: " + list);
// 判断元素是否存在
if (list.contains("banana")) {
System.out.println("The list contains banana.");
} else {
System.out.println("The list does not contain banana.");
}
// 清空列表
list.clear();
System.out.println("After clearing the list, the size of the list is: " + list.size());
}
}
运行程序输出结果如下:
The size of the list is: 3
The first element of the list is: apple
Now the first element of the list is: pear
After removing the third element, the list is: [pear, banana]
The list contains banana.
After clearing the list, the size of the list is: 0
在此示例中,我们首先通过 new ArrayList<String>()
初始化了一个 ArrayList
对象,其泛型参数为字符串类型。()
然后,我们使用 add()
方法向列表中添加元素;
使用 size()
方法获取列表长度;
使用 get()
方法访问列表中的元素;
使用 set()
方法修改列表中的元素;
使用 remove()
方法删除列表中的元素;
使用 contains()
方法判断元素是否存在于列表中;
使用 clear()
方法清空列表。