Java 接口Collection的ArrayList实现类

ArratList实现类

Collection是最高层集合接口,Arraylist是其中的一个实现类

ArrayList常用方法

  • add()
    添加元素

  • clear()
    清空集合

  • remove()
    删除集合某个元素

  • contains()
    判断集合是否包含某个元素,返回值为boolean类型

  • equals()
    比较两集合内容是否一致

遍历

  1. 集合类不能使用普通for循环,无法索引遍历
  2. 增强for循环可以遍历集合
  3. 利用迭代器(Iterator())可以遍历集合

实例

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Test01 {
    public static void main(String[] args) {
        Collection col = new ArrayList();
        Collection col2 = new ArrayList();
        col.add("abc");  //添加元素
        col.add(12);
        col2.add("abc");
        System.out.println(col.size()); //返回集合长度
        col.remove(12); //删除某元素
        System.out.println(col.contains("abc")); //判断是否包含某元素
        System.out.println(col.equals(col2)); //判断两集合内容是否一致
       
        for(Object o:col){  //增强for循环遍历集合
            System.out.println(o);
        }

   Iterator iterator = col.iterator(); //迭代器遍历集合
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

扩充

Collection子接口List
相比于Collection,List重载了几个比较常用的方法

  • add(index,obj)
    在第index位置添加obj元素

  • remove(index)
    删除第index位置元素,若index与某个元素内容相同,则优先执行删除位置为index位置元素

  • get(index)
    返回index位置元素

  • set(index,obj1)
    将index位置元素修改为obj1

相比于Collection,List可以使用普通for循环遍历

实例

public class Test01 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("abc");
        list.add(123);
        list.add(1,"x"); //在下标1位置插入"x"
        System.out.println(list);
        list.remove(0); //删除下标0元素
        System.out.println(list);
        list.set(0,"y");//将下表为0元素改为"y"
        for (int i = 0; i < list.size(); i++) { //普通for循环遍历
            System.out.println(list.get(i));
        }
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值