Java—Collections

目录

1. Collections

1.1Collections概述和使用

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


1. Collections

1.1Collections概述和使用

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

Collections类的常用方法
        publicstatic<T extends Comparable<?superT>> voidsort(List<T>list):将指定的列表按升序排序

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

package zyy07;


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

public class Demo {
    public static void main(String[] args) {
        //创建集合类型
        List<Integer> 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<student> 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<student>() {
            @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());
        }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值