集合:Collection(List、Queue、Set)

集合

是Java中提供的一种容器,可以用来存储多个数据

集合和数组都是容器,区别是:

  • 数组的长度是固定的 — 集合的长度是可变的
  • 数组中存储的是同一类型的元素,可以储存基本数据类型值 — 集合存储的都是对象,而且对象的类型可以不一致

Collection - 单列集合

Collection(I)(集合,是接口)
父接口:Iterable

List(I) -> 顺序结构(数组和链表)
     ArrayList - 数组
     LinkedList - 双向链表
     Vector - 数组
Queue(I) -> 队列结构(普通队列)
     Deque(I) 队列结构(双端队列, 栈)
         LinkedList
Set(I) -> 散列结构(没有顺序)
     HashSet
     SortedSet(I)
         TreeSet - 二叉树

常用API
add、remove、contains、isEmpty、clear

       Collection<String> col = new ArrayList<>();
        // 添加元素
        col.add("haha");
        col.add("xixi");
        col.add("heihei");
        System.out.println(col); // [haha, xixi, heihei]
        // 移除指定元素
        col.remove("xixi");
        System.out.println(col); // [haha, heihei]
        // 是否包含指定元素
        boolean is = col.contains("hehe");
        System.out.println(is); // false
        // 是否为空 size() == 0
        System.out.println(col.isEmpty()); // false
        // 清空集合
        col.clear();
        System.out.println(col); // []

remove(细节问题)
contains也是一样

        Collection<Student> col = new ArrayList<>();
        Student s1 = new Student("张老三", 34);
        Student s2 = new Student("李老六", 43);
        col.add(s1);
        col.add(s2);
        // [Student{name='张老三', age=34}, Student{name='李老六', age=43}]
        System.out.println(col);

        Student s3 = new Student("张老三", 34);
        col.remove(s3);
        // 内部调用equals方法判断对象是否一致(equals已修改,只要名字跟年龄相同,则对象就相同) 
        System.out.println(col); // [Student{name='李老六', age=43}]

addAll、containsAll、retainAll、removeAll
(参数是Collection类型)

        Collection<String> col1 = new ArrayList<>();
        col1.add("小李飞刀");
        col1.add("西门吹雪");
        Collection<String> col2 = new ArrayList<>();
        col2.add("令狐冲");
        col2.add("任盈盈");
        // 将col2中所有的元素加到col1中
        col1.addAll(col2);
        System.out.println(col1); // [小李飞刀, 西门吹雪, 令狐冲, 任盈盈]

        Collection<String> col3 = new ArrayList<>();
        col3.add("东方不败");
        col3.add("令狐冲");
        // 问col1中是否包含col3中的所有元素
        boolean b = col1.containsAll(col3);
        System.out.println(b); // false

        Collection<String> col4 = new ArrayList<>();
        col4.add("任我行");
        col4.add("任盈盈");
        col4.add("令狐冲");
        // 将col1中元素仅保留col4中出现的元素
        col1.retainAll(col4);
        System.out.println(col1); // [令狐冲, 任盈盈]
        
        Collection<String> col5 = new ArrayList<>();
        col5.add("东方不败");
        col5.add("令狐冲");
        // 将col5中出现过的元素从col1里面移除掉
        col1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值