ArrayList的使用

ArrayList(重点)的特点

  • 存储结构:数组,查找遍历速度快,增删慢

1.增加元素

        //创建集合
        ArrayList arrayList=new ArrayList();

        //1.增加元素
        Student s1=new Student("刘德华",20);
        Student s2=new Student("郭富城",24);
        Student s3=new Student("梁朝伟",21);
        Student s4=new Student("周星驰",25);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        arrayList.add(s4);
        System.out.println("集合元素个数:"+arrayList.size());
        System.out.println(arrayList.toString());

2.删除元素

        //2.删除元素
        arrayList.remove(s1);
        arrayList.clear();//清空集合
        arrayList.remove(new Student("郭富城",24));//重写equals方法,使得新增一种删除元素方法
        System.out.println("删除后的元素个数为:"+arrayList.size());
        System.out.println(arrayList.toString());

重写的equals方法

    @Override
    public boolean equals(Object o) {//重写equals方法
        if (this == o) //1.判断是否为同一个元素
            return true;
        if(o==null){//2.判断是否为空
            return false;
        }
        //3.判断是否为Student类型
        if(o instanceof Student){
            Student s=(Student) o;
            //4.比较属性
            if(this.name.equals(s.getName())&&this.age==s.getAge()){
                return true;
            }
        }
        //5.不满足条件则返回false
        return false;
    }

3.遍历元素(重点)


3.1 简单迭代器

        //3.1 简单迭代器
        Iterator it=arrayList.iterator();
        while(it.hasNext()){
            Student s=(Student) it.next();//把object类型转成student类型输出
            System.out.println(s.toString());
        }

3.2 列表迭代器

        //3.2 列表迭代器(顺序)
        ListIterator lit=arrayList.listIterator();
        while (lit.hasNext()){
            Student s=(Student) lit.next();
            System.out.println(s.toString());
        }

4.判断

        //4.判断
        System.out.println(arrayList.contains(s1));//集合是否包含此元素
        
        System.out.println(arrayList.contains(new Student("刘德华",20)));
        //建立在重写equals方法的基础上
        System.out.println(arrayList.isEmpty());//集合是否为空

5.查找元素下标位置

        //5.查找元素下标位置
        System.out.println(arrayList.indexOf(new Student("梁朝伟",21)));
        //建立在重写equals方法的基础上
        System.out.println(arrayList.indexOf(s1));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值