比较器Comparator

Comparator接口

java中有内置的排序,Arrays.sort(),现在我有一个Student类,类中三个成员变量name,id,age,我现在想以age作为参考进行升序排序,应该如何做,很简单,只需要自己定义一个类实现Comparator接口即可

import java.util.*;
class Student {
	String name;
	int id,age;
	Student(String name,int id,int age) {
		this.name = name;
		this.id = id;
		this.age = age;
	}
}
public class ComparetorTest {
	public static class MyCompara implements Comparator<Student> {
		public int compare(Student s1, Student s2) {
			return s1.age - s2.age;
		}
	}
	public static void main(String[] args) {
		Student s1 = new Student("A",1,22);
		Student s2 = new Student("B",3,23);
		Student s3 = new Student("C",2,21);
		Student[] student = new Student[] {s1,s2,s3};
		Arrays.sort(student, new MyCompara());
		for(int i = 0;i < student.length;i++) 
			System.out.println(student[i].name + " " + student[i].id + " " + student[i].age);
	}
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注