一、概念
ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素。
二、创建方式
import java.util.ArrayList; // 引入 ArrayList 类
ArrayList<E> objectName =new ArrayList<>(); // 初始化
- E: 泛型数据类型,用于设置 objectName 的数据类型,只能为引用数据类型。
- objectName: 对象名。
三、使用方法
import java.util.ArrayList;
import java.util.List;
public class CollectionExample {
private List<String> items;
// 构造函数,初始化集合
public CollectionExample() {
items = new ArrayList<>();
}
// 添加元素
public void addItem(String item) {
items.add(item);
System.out.println(item + " has been added.");
}
// 删除元素
public void removeItem(String item) {
if (items.remove(item)) {
System.out.println(item + " has been removed.");
} else {
System.out.println(item + " not found.");
}
}
// 访问元素
public String getItem(int index) {
if (index >= 0 && index < items.size()) {
return items.get(index);
} else {
return "Index out of bounds.";
}
}
// 更改元素
public void updateItem(int index, String newItem) {
if (index >= 0 && index < items.size()) {
items.set(index, newItem);
System.out.println("Item at index " + index + " has been updated to " + newItem + ".");
} else {
System.out.println("Index out of bounds.");
}
}
// 打印所有元素
public void printItems() {
System.out.println("Current items in the collection: " + items);
}
// 主方法用于测试
public static void main(String[] args) {
CollectionExample collection = new CollectionExample();
// 添加元素
collection.addItem("Apple");
collection.addItem("Banana");
collection.addItem("Orange");
// 打印当前元素
collection.printItems();
// 访问元素
System.out.println("Item at index 1: " + collection.getItem(1));
// 更新元素
collection.updateItem(1, "Mango");
// 打印更新后的元素
collection.printItems();
// 删除元素
collection.removeItem("Apple");
collection.printItems();
}
}
运行结果:
Apple has been added.
Banana has been added.
Orange has been added.
Current items in the collection: [Apple, Banana, Orange]
Item at index 1: Banana
Item at index 1 has been updated to Mango.
Current items in the collection: [Apple, Mango, Orange]
Apple has been removed.
Current items in the collection: [Mango, Orange]