public class Student implements Comparable<Student>{
private String name;
private int 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 Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student student) {
return this.getAge()-student.getAge();
}
}
上面代码是创建的学生类,要求有一个学生对象数组,按年龄从小到大排序:
测试类:
public class Test {
public static void main(String[] args) {
Student[] students=new Student[3];
students[0]=new Student("张三",24);
students[1]=new Student("李四",6);
students[2]=new Student("王五",30);
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(Arrays.toString(students));
}
public static Comparable<Student> getMax(Comparable<Student> c1,Comparable<Student> c2){
int result=c1.compareTo((Student) c2);
if(result==0){
return c1;
} else if (result>0) {
return c1;
}else {
return c2;
}
}
}
运行结果:
对日期进行排序
在Student加入生日属性:
public class Student implements Comparable<Student>{
private String name;
private int age;
private LocalDate birthDay;
public LocalDate getBirthDay() {
return birthDay;
}
public void setBirthDay(LocalDate birthDay) {
this.birthDay = birthDay;
}
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 Student(String name, int age,LocalDate localDate) {
this.name = name;
this.age = age;
this.birthDay=localDate;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", birthDay=" + birthDay +
'}';
}
@Override
public int compareTo(Student student) {
return this.getAge()-student.getAge();
}
}
测试类如下:
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
Student[] students=new Student[3];
students[0]=new Student("张三",24,LocalDate.of(2000,11,9));
students[1]=new Student("李四",6,LocalDate.of(1998,2,20));
students[2]=new Student("王五",30,LocalDate.of(2003,9,11));
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// return o1.getBirthDay().compareTo(o2.getBirthDay());
return o2.getBirthDay().compareTo(o1.getBirthDay());
}
});
System.out.println(Arrays.toString(students));
}
public static Comparable<Student> getMax(Comparable<Student> c1,Comparable<Student> c2){
int result=c1.compareTo((Student) c2);
if(result==0){
return c1;
} else if (result>0) {
return c1;
}else {
return c2;
}
}
}
运行结果: