ArrayList类的几个方法

该博客展示了如何使用Java的ArrayList进行元素的添加、遍历、判断、查找和删除操作。通过普通迭代器和列表迭代器实现了正序和逆序遍历,并演示了contains方法、indexOf方法以及remove方法的用法。
摘要由CSDN通过智能技术生成
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class ArrayListTest {
    public static void main(String[] args) {
        student s1 =new student("惶惶",21);
        student s2 =new student("人世",21);
        student s3 =new student("不可推磨",21);
        ArrayList arrayList =new ArrayList();

        System.out.println("---------添加元素----------");
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        System.out.println(arrayList);


        System.out.println("---------遍历元素----------");
        System.out.println("---------普通迭代器遍历----------");
        Iterator iterator =arrayList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("---------列表迭代器遍历----------");
        ListIterator listIterator =arrayList.listIterator();
        System.out.println("逆序:");
        for (;listIterator.hasNext();) {
            listIterator.next();
        }
        while (listIterator.hasPrevious()){
            System.out.println(listIterator.previous());
        }
        System.out.println("顺序:");
        while (listIterator.hasNext()){
            System.out.println(listIterator.next());
        }

        System.out.println("---------判断----------");
        System.out.println("是否包含对象s1:"+arrayList.contains(s1));
        System.out.println("是否包含对象(人世,21):"+arrayList.contains(new student("人世",21)));
        System.out.println("集合是否为空:"+arrayList.isEmpty());

        System.out.println("---------查找----------");
        System.out.println(arrayList.indexOf(s1));
        System.out.println(arrayList.indexOf(new student("不可推磨",21)));

        System.out.println("---------删除元素----------");
        arrayList.remove(new student("惶惶",21));
        System.out.println(arrayList);

    }
}

输出结果:

---------添加元素----------
[student[name='惶惶', age=21], student[name='人世', age=21], student[name='不可推磨', age=21]]
---------遍历元素----------
---------普通迭代器遍历----------
student[name='惶惶', age=21]
student[name='人世', age=21]
student[name='不可推磨', age=21]
---------列表迭代器遍历----------
逆序:
student[name='不可推磨', age=21]
student[name='人世', age=21]
student[name='惶惶', age=21]
顺序:
student[name='惶惶', age=21]
student[name='人世', age=21]
student[name='不可推磨', age=21]
---------判断----------
是否包含对象s1:true
是否包含对象(人世,21):true
集合是否为空:false
---------查找----------
0
2
---------删除元素----------
[student[name='人世', age=21], student[name='不可推磨', age=21]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值