没有合适的资源?快使用搜索试试~ 我知道了~
java比较器的常见用法.pdf
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 40 浏览量
2021-10-02
11:50:28
上传
评论
收藏 62KB PDF 举报
温馨提示
试读
11页
java比较器的常见用法.pdf
资源推荐
资源详情
资源评论
计算机交流平台:计算机故障 _计算机论坛 www.it168bbs.com wy
java 比较器的常见用法
Comparable 接口的作用
之前 Arrays 类中存在 sort()方法,此方法可以直接对对象数组进行排序。
Comparable 接口
可以直接使用 java.util.Arrays 类进行数组的排序操作,但对象所在的类必须实现 Comparable
接口,用于指定排序接口。
Comparable 接口的定义如下:
public interface Comparable<T>{
public int compareTo(T o);
}
此方法返回一个 int 类型的数据,但是此 int 的值只能是一下三种:
1:表示大于
-1:表示小于
0:表示相等
要求:定义一个学生类,里面有姓名,年龄,成绩三个属性,要求按成绩由高到低排序,如
果成绩相等,则按照年龄由低到高排序。
[java] package com.itmyhome;
import java.util.Arrays;
class Student implements Comparable<Student>{
private String name;
private int age;
private float score;
public Student(String name,int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student stu) { //覆写 compareTo 方法实现排序规则的应用
if(this.score>stu.score){
return -1;
}else if(this.score<stu.score){
return 1;
}else{
if(this.age>stu.age){
return 1;
}else if(this.age<stu.age){
计算机交流平台:计算机故障 _计算机论坛 www.it168bbs.com wy
return -1;
}else{
return 0;
}
}
}
public String toString(){
return " 姓名: "+this.name+", 年龄: "+this.age+", 成绩: "+this.score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
public class T {
public static void main(String[] args) throws Exception{
Student stu[] = {new Student(" 张三 ",22,80f)
,new Student(" 李四 ",23,83f)
,new Student(" 王五 ",21,80f)};
Arrays.sort(stu); //进行排序操作
for (int i = 0; i < stu.length; i++) {
Student s = stu[i];
System.out.println(s);
}
计算机交流平台:计算机故障 _计算机论坛 www.it168bbs.com wy
}
}
package com.itmyhome;
import java.util.Arrays;
class Student implements Comparable<Student>{
private String name;
private int age;
private float score;
public Student(String name,int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Student stu) { //覆写 compareTo 方法实现排序规则的应用
if(this.score>stu.score){
return -1;
}else if(this.score<stu.score){
return 1;
}else{
if(this.age>stu.age){
return 1;
}else if(this.age<stu.age){
return -1;
}else{
return 0;
}
}
}
public String toString(){
return " 姓名: "+this.name+", 年龄: "+this.age+", 成绩: "+this.score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
剩余10页未读,继续阅读
资源评论
资料大全
- 粉丝: 14
- 资源: 26万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功