对象类
package com.lf.java.basic.interfaces;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Student implements Comparable<Student>,Cloneable{
private String name;
private int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student s) {
return Integer.compare(s.getAge(),age);
}
}
排序测试
package com.lf.java.basic.interfaces;
import java.util.Arrays;
import java.util.Comparator;
public class StudentArrayDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Student[] students = new Student[10];
int i = 0;
while (i < 10) {
Student student = new Student();
// Object clone = student.clone();
// if(clone instanceof Student){
// Student cloneStudent = (Student)clone;
// }
student.setAge(i);
student.setName("张" + i);
students[i] = student;
i++;
}
Arrays.sort(students);//基于Comparable接口排序
Arrays.sort(students,(o1, o2) -> o2.getAge()-o1.getAge());//逆序
Arrays.sort(students, Comparator.comparingInt(Student::getAge));//顺序
for (Student s : students) {
System.out.println(s.toString());
}
}
}
输出
Student{name=‘张0’, age=0}
Student{name=‘张1’, age=1}
Student{name=‘张2’, age=2}
Student{name=‘张3’, age=3}
Student{name=‘张4’, age=4}
Student{name=‘张5’, age=5}
Student{name=‘张6’, age=6}
Student{name=‘张7’, age=7}
Student{name=‘张8’, age=8}
Student{name=‘张9’, age=9}