• Java—Collections


    目录

    1. Collections

    1.1Collections概述和使用

    案例:ArrayList存储学生对象并排序


    1. Collections

    1.1Collections概述和使用

    Collections类的概述
            是针对集合操作的工具类

    Collections类的常用方法
            publicstatic> voidsort(Listlist):将指定的列表按升序排序

            publicstatic void reverse(Listlist):反转指定列表中元素的顺序
            publicstatic void shuffle(Listlist):使用默认的随机源随机排列指定的列表

    1. package zyy07;
    2. import java.util.ArrayList;
    3. import java.util.Collections;
    4. import java.util.List;
    5. public class Demo {
    6. public static void main(String[] args) {
    7. //创建集合类型
    8. List l=new ArrayList<>();
    9. //添加元素
    10. l.add(12);
    11. l.add(15);
    12. l.add(14);
    13. l.add(6);
    14. //Collections.sort()将指定列表按升序
    15. //Collections.sort(l);
    16. //Collections.reverse()反转
    17. //Collections.reverse(l);
    18. //Collections.shuffle()随机排序
    19. Collections.shuffle(l);
    20. System.out.println(l);
    21. }
    22. }

    案例:ArrayList存储学生对象并排序

    需求:ArrayList存储学生对象,使用Collections对ArrayList进行排序
            要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

    思路:
            定义学生类
            创建ArrayList集合对象
            创建学生对象
            把学生添加到集合
            使用Collections对ArrayList集合排序

            遍历集合

    1. package com.test;
    2. import java.util.ArrayList;
    3. import java.util.Collections;
    4. import java.util.Comparator;
    5. public class studentdemo {
    6. public static void main(String[] args) {
    7. //创建集合对象
    8. ArrayList a=new ArrayList<>();
    9. //创建学生对象
    10. student s1=new student("zyy",10);
    11. student s2=new student("zy",11);
    12. student s3=new student("z",12);
    13. student s4=new student("z",12);
    14. //把学生添加到集合
    15. a.add(s1);
    16. a.add(s2);
    17. a.add(s3);
    18. a.add(s4);
    19. //排序
    20. //Collections.sort(a);出现错误
    21. Collections.sort(a, new Comparator() {
    22. @Override
    23. public int compare(student s1, student s2) {
    24. int num=s1.getAge()-s2.getAge();
    25. int num1=num==0?s1.getName().compareTo(s2.getName()):num;
    26. return num1;
    27. }
    28. });
    29. //遍历集合
    30. for(student s:a ){
    31. System.out.println(s.getName()+","+s.getAge());
    32. }
    33. }
    34. }

  • 相关阅读:
    firefox的主题文件位置在哪?记录以防遗忘
    Linux中的防火墙(粗糙版)
    (学习日报)2022.7.20
    五年Python从业者,谈谈Python的一些优缺点
    Oracle 中的伪列
    Spring Security CSRF 保护指南
    区块链学姐:8月9日以太持续破新高,空头能量是否还存在?
    自学Python 60 socketserver编程
    增强团队创新力需要打造多样性团队
    开机优化加速
  • 原文地址:https://blog.csdn.net/qq_62799214/article/details/126233966