java基础——集合Arraylist

一、概念

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] 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值