Java—Collections

目录

1. Collections

1.1Collections概述和使用

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


1. Collections

1.1Collections概述和使用

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

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

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

package zyy07;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        //创建集合类型
        List l=new ArrayList<>();
        //添加元素
        l.add(12);
        l.add(15);
        l.add(14);
        l.add(6);
        //Collections.sort()将指定列表按升序
        //Collections.sort(l);

        //Collections.reverse()反转
        //Collections.reverse(l);

        //Collections.shuffle()随机排序
        Collections.shuffle(l);
        System.out.println(l);

    }
}

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

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

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

        遍历集合

package com.test;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class studentdemo {

    public static void main(String[] args) {
        //创建集合对象
        ArrayList a=new ArrayList<>();
        //创建学生对象
        student s1=new student("zyy",10);
        student s2=new student("zy",11);
        student s3=new student("z",12);
        student s4=new student("z",12);
        //把学生添加到集合
        a.add(s1);
        a.add(s2);
        a.add(s3);
        a.add(s4);
        //排序
        //Collections.sort(a);出现错误
        Collections.sort(a, new Comparator() {
            @Override
            public int compare(student s1, student s2) {
                int num=s1.getAge()-s2.getAge();
                int num1=num==0?s1.getName().compareTo(s2.getName()):num;
                return num1;
            }
        });
        //遍历集合
        for(student s:a ){
            System.out.println(s.getName()+","+s.getAge());
        }

    }
}

你可能感兴趣的:(Java,servlet,java,mybatis)