ArrayList集合的get(),set(),subList(),forEach()

文章介绍了Java中如何使用Eget通过索引获取列表元素,Eset修改指定位置的元素,以及subList方法截取列表子集。同时,展示了使用forEach和Lambda表达式进行列表遍历的方法。示例代码中,通过gePageList函数获取列表的指定区间并输出。
摘要由CSDN通过智能技术生成

E get (int index) 通过索引获取元素
也可以用来遍历

在这里插入图片描述


E set (int index,E element) 修改指定位置的元素

在这里插入图片描述

输出
[a, d, c]


sublist(int startndex ,int endIndex)

获取下从startIndex到endIndex的元素
包括startIndex位置 不括号endIndex位置
注意判断索引是否越界

public class Test {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        List<Integer> result = gePageList(list,2,3);
        System.out.println(result);
    }
    public static List<Integer> gePageList(List<Integer> list,int startIndex,int endIndex) {
        if (startIndex > endIndex) {
            throw new IllegalArgumentException("startIndex必须小于等于endIndex");
        }
        if (startIndex < 0) {
            throw new IllegalArgumentException("startIndex必须大于等于0");
        }
        if (endIndex > list.size()) {
            throw new IllegalArgumentException("endIndex超过了集合范围");
        }
        List<Integer> result = list.subList(startIndex,endIndex);
        return result;
    }
}
输出
[3]

-------------------------------
forEach()   Lambda表达式
![在这里插入图片描述](https://img-blog.csdnimg.cn/a95653b598ea4f039826a05be9d1e168.png)


----------------------------------------------------------------
![在这里插入图片描述](https://img-blog.csdnimg.cn/7b709f77f6564c55a5a79e76860731c5.png)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值