Java中比较器的使用

很多情况下,我们需要对数据进行排序,但是java自带的比较器只能比较基本数据类型,比如我们自己定义一个Student类,如果用默认的Array.sort()方法进行排序,他会按照内存地址进行排序,那么这个排序毫无意义,此时我们就需要自己定义一个比较器,按照我们想要的比较方式来进行排序。
我们需要定义一个比较器,实现java.util.Comparator接口,会需要重写一个compare()方法,如下

public static  class CustomeComparator implements Comparator<Student>{
		// 根据学生成绩进行排序
		@Override
		public int compare(Student st1, Student st2) {
			return st1.socre-st2.socre;
		}
	}

这就是一个基本的比较器,其返回值分三种

负数:		前者 < 后者
0:			两者相等
正数:		前者 > 后者
public static void main(String[] args) {
		Student student1 = new Student("A", 18, 76);
		Student student2 = new Student("B", 22, 85);
		Student student3 = new Student("C", 31, 64);
		Student[] students = new Student[] { student1, student2, student3 };
		for (Student student : students) {
			System.out.println(student);
		}
		System.out.println("------ 排序后 --------");
		Arrays.sort(students, new CustomeComparator());
		for (Student student : students) {
			System.out.println(student);
		}
	}

使用的时候直接把需要排序的数组和自定义比较器丢进sort()即可,可以看看打印前后的顺序。对Array.sort()和Collections.sort()不太了解的朋友可以去自行百度,我这里不做过多解释。

Student [name=A, age=18, socre=76]
Student [name=B, age=22, socre=85]
Student [name=C, age=31, socre=64]
------ 排序后 --------
Student [name=C, age=31, socre=64]
Student [name=A, age=18, socre=76]
Student [name=B, age=22, socre=85]

一个简单的比较器就完成了,可以根据自己的需求进行定制。
后面贴出完整代码:

import java.util.Arrays;
import java.util.Comparator;

public class MyComparator {
	
	public static class Student{
		public String name;
		public int age;
		public int socre;
		public Student(String name, int age, int socre) {
			super();
			this.name = name;
			this.age = age;
			this.socre = socre;
		}

		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + ", socre=" + socre + "]";
		}
		
	}
	
	public static  class CustomeComparator implements Comparator<Student>{
		// 根据学生成绩进行排序
		@Override
		public int compare(Student st1, Student st2) {
			return st1.socre-st2.socre;
		}
	}
	
	public static void main(String[] args) {
		Student student1 = new Student("A", 18, 76);
		Student student2 = new Student("B", 22, 85);
		Student student3 = new Student("C", 31, 64);

		Student[] students = new Student[] { student1, student2, student3 };
		
		for (Student student : students) {
			System.out.println(student);
		}
		System.out.println("------ 排序后 --------");

		Arrays.sort(students, new CustomeComparator());
		
		for (Student student : students) {
			System.out.println(student);
		}
	}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值