JAVASE —— 09集合框架

什么是集合

  • 概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。

  • 和数组的区别:

  • 数组长度固定,集合长度不固定

  • 数数组可以存储基本类型和引用类型,集合只能存储引用类型

  • 位置:java.util.*;


Collection体系集合

Collection接口

  • 特点:代表一组任意类型的对象,无序、无下标、不能重复。

  • 方法:

  • boolean add(Object obj) //添加一个对象。

  • boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中。

  • void clear() //清空此集合中的所有对象。

  • boolean contains(Object o) //检查此集合中是否包含o对象

  • boolean equals (Object o) //比较此集合是否与指定对象相等。

  • boolean isEmpty() //判断此集合是否为空

  • boolean remove(Object o) //在此集合中移除o对象

  • int size() //返回此集合中的元素个数。

  • Object[] toArray() //将此集合转换成数组。

public class Demo1 {
    public static void main(string[] args){
        Collection collection = new ArrayList();
        //1.添加元素
        cllection.add("苹果");
        cllection.add("榴莲");
        System.out.println(collection);
        //2.删除元素
        collection.remove("苹果");
        //3.遍历元素
        //3.1使用增强for
        for (Object object : collection) {
            System.out.println(object);
        }
        //3.2使用迭代器
        //hasNext()有没有下一个元素
        //next();获取下一个元素
        //remove();删除当前元素
        Iterator it = collection.iterator();
        while(it.hasNext()) {
            String s = (String)it.next();
            System.out.println(s);
            //迭代中不能使用collection删除方法
            //collection.remove(s);
            it.remove();
        }
        //4.判断
        System.out.println(collection.contains("西瓜"));
        System.out.println(collection.isEmpty());
    }
}

List接口

  • 特点:有序、有下标、元素可以重复。

  • 方法

  • void add(int index,Object o) //在index位置插入对象o。

  • boolean addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置。

  • Object get(int index) //返回集合中指定位置的元素。

  • List subList(int fromIndex,int toIndex) //返回fromIndex和toIndex之间的集合元素。

public class Demo2 {
    public static void main(string[] args){
        List list = new ArrayList<>();
        //1.添加元素
        list.add("苹果");
        //2.删除元素
        list.remove("苹果");
        //3遍历
        //3.1使用for遍历
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
        //3.2使用增强for
        for(Object object : list){
            System.out.pri
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值