ArrayList类的简单介绍

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() 方法清空列表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值