/* * 比较器的使用,实现 Comparable接口 * 功能:实现对象的多条件比较 */ package com.array; import java.util.Arrays; public class compareto { public static void main(String[] args){ Student arrStu[] = { new Student("王明",10,55), new Student("孙丽", 50, 55), new Student("李剑",20, 80)}; Arrays.sort(arrStu); for(int i=0;i<arrStu.length;i++){ System.out.println(arrStu[i]); } } } class Student implements Comparable<Student>{ private String name=""; private int age =0; private float 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 Student(String name,int age,float score){ this.setName(name); this.setAge(age); this.setScore(score); } public String toString(){ return this.getName()+" 分数:"+this.getScore()+" 年龄:"+this.getAge(); } public int compareTo(Student stu){ //1>先比较分数 if(this.getScore()>stu.getScore()){ return 1; }else if(this.getScore()<stu.getScore()){ return -1; }else { //2>再比较年龄 if(this.getAge()>stu.getAge()){ return 1; }else if(this.getAge()<stu.getAge()){ return -1; }else{ return 0; } } } }
比较器的使用,实现 Comparable接口,功能:实现对象的多条件比较,排序
原创
©著作权归作者所有:来自51CTO博客作者xiaohongyangok的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java中for循环使用方式的比较
Java中for循环使用方式的比较
for循环 Java -
Java对象的比较Comparable与Comparator
写在前面,Java基础系列文章都是作者基于b站尚硅谷的Java基础视频所做的笔记,没有时间的同学可以认真看看,如
java comparator 面向对象编程 ide 自定义类 -
java中Comparable实现对象的比较
/*
向上转型 类关系 泛型 数据 html -
(68)TreeSet练习:两种排序方式:自然排序(实现comparable接口)、比较器
Set: —–TreeSet类可以对se...
比较器 构造函数 二叉树 数据结构 调用方法