Java中的比较器Comparable、Comparator
参考博客:java学习笔记13--比较器(Comparable、Comparator)
在Java代码中,我们常常会面临需要对集合进行排序的情况,这种情况下我们需要手动的定义Java比较器,告诉程序两个对象如何比较大小。
Java中的比较器分为两种Comparable和Comparator:
- Comparable:实现Comparable接口,并且重写compareTo(T o)方法
- Comparator:实现Comparator接口,并且重写compare()和equals()方法
Comparable实现
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;
}
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);
}
}
}
Compartor
package com.itmyhome;
import java.util.Comparator;
public class MyComparator implements Comparator<Student> { //实现比较器
@Override
public int compare(Student stu1, Student stu2) {
// TODO Auto-generated method stub
if(stu1.getAge()>stu2.getAge()){
return 1;
}else if(stu1.getAge()<stu2.getAge()){
return -1;
}else{
return 0;
}
}
}
class Student {
private String name;
private int age;
public Student(String name,int age ){
this.name = name;
this.age = age;
}
public String toString(){
return "姓名:"+this.name+", 年龄:"+this.age;
}
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 class T {
public static void main(String[] args) throws Exception{
Student stu[] = {new Student("张三",23)
,new Student("李四",26)
,new Student("王五",22)};
Arrays.sort(stu,new MyComparator()); //对象数组进行排序操作
List<Student> list = new ArrayList<Student>();
list.add(new Student("zhangsan",31));
list.add(new Student("lisi",30));
list.add(new Student("wangwu",35));
Collections.sort(list,new MyComparator()); //List集合进行排序操作
for (int i = 0; i < stu.length; i++) {
Student s = stu[i];
System.out.println(s);
}
System.out.println("*********");
for (int i=0;i<list.size();i++){
Student s = list.get(i);
System.out.println(s);
}
}
}