Java学习笔记 Collection集合

本文深入探讨了Java集合框架中的Collection接口及其核心方法,包括添加、删除、查询元素等操作,并通过示例代码展示了如何使用ArrayList实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.itcast.demo;

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

/*- public boolean add(E e):  把给定的对象添加到当前集合中 。
- public void clear() :清空集合中所有的元素。
- public boolean remove(E e): 把给定的对象在当前集合中删除。
- public boolean contains(E e): 判断当前集合中是否包含给定的对象。
- public boolean isEmpty(): 判断当前集合是否为空。
- public int size(): 返回集合中元素的个数。
- public Object[] toArray(): 把集合中的元素,存储到数组中。
*/
public class Demo01Collection {
    public static void main(String[] args) {
        //创建集合对象
        Collection<String> coll = new ArrayList<>();//多态
        System.out.println(coll);//[] 重写了toString方法
        boolean b1 = coll.add("张三");
        System.out.println(b1);//true,一般不需要接收,都是true
        coll.add("李四");
        coll.add("王五");
        coll.add("赵六");
        coll.add("田七");
        System.out.println(coll);//[张三, 李四, 王五, 赵六, 田七]
        System.out.println("================");
        //remove方法,返回布尔值,若存在元素,则删除元素返回true,若不存在,删除失败 返回false
        boolean b2 = coll.remove("赵六");//true
        boolean b3 = coll.remove("赵四");//false
        System.out.println(coll);
        System.out.println("================");
        //contains 方法 包含返回true
        boolean b4 = coll.contains("李四");//true
        boolean b5 = coll.contains("赵四");//false
        System.out.println(b4);
        System.out.println(b5);
        System.out.println("================");

        boolean b6 = coll.isEmpty();//非空false
        System.out.println(b6);
        System.out.println("==================");

        int size = coll.size();
        System.out.println(size);
        System.out.println("================");

        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        System.out.println("================");

        //clear方法清除所有元素,但是集合仍然存在

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值