Java中的Collection和Collections是啥关系?Collections中常用的静态方法有哪些,调用sort()方法重写compareTo()方法

Collection和Collections是啥关系?

Collection是集合接口
Collections是集合的操作类


Collections中常用的静态方法

sort()

1.可以对集合进行排序,不能对复杂的集合排序,需要先制定排序规则(重写compareTo()方法)

2.实现一个类的对象之间比较大小

实现步骤

1.该类要重写Comparable接口的compareTo()方法
2.自定义比较规则
返回值:相等,返回0;大于,返回1;小于,返回-1

//实现Comparable接口
public class Student implements Comparable 
//重写compareTo()方法
public int compareTo(Object Object){
    Student student = (Student)Object;//操作前必须强制转型
    if(this.sid<student.sid){
        return -1;
    }else if(this.sid>student.sid){
        return 1;
    }else {
        return 0;
    }
}

2.调用sort()方法

//使用Collections中的sort()方法进行排序
Collections.sort(stuSet);
//for循环遍历集合
for (int i=0;i<stuSet.size();i++){
    Student student = (Student) stuSet.get(i);
    System.out.println(student.getSid()+"--"+student.getName());
}

max()/min()
binarySearch()
reverse()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值