Comparable接口的使用
程序员文章站
2023-12-26 15:48:57
...
1、当数据需要排序时,我们可以用这个接口进行排序。
2、代码样例
public class Student implements Comparable<Student>{
private int id;
private String name;
private int age;
public Student() {
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
System.out.println("调用方法");
if(this.id<o.id){
return -1;
}else if (this.id>o.id){
return 1;
}else {
if (this.age<o.age){
return -1;
}else if (this.age<o.age){
return 1;
}else return 0;
}
}
}
public class Test03 {
public static void main(String[] args) {
List<Student> students=new ArrayList<>();
Student s1=new Student(1,"刘德华",18);
Student s2=new Student(1,"张学友",20);
Student s3=new Student(2,"郭富城",25);
Student s4=new Student(3,"黎明",25);
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
for (Student s:students){
System.out.println(s.toString());
}
Collections.sort(students);//自动调用compareTo
for (Student s:students){
System.out.println(s.toString());
}
}
}
3、代码输出结果
Student{id=1, name='刘德华', age=18}
Student{id=1, name='张学友', age=20}
Student{id=2, name='郭富城', age=25}
Student{id=3, name='黎明', age=25}
调用方法
调用方法
调用方法
Student{id=1, name='刘德华', age=18}
Student{id=1, name='张学友', age=20}
Student{id=2, name='郭富城', age=25}
Student{id=3, name='黎明', age=25}
4、代码解释
在集合Collection和Arrays类中,都有sort()方法,可以对于集合和数组进行排序,sort方法实现了Comparable的接口,调用了自然方法。我们可以再student类里实现Comparable接口,重写他的排序方法,sort会自动调用,实现排序的功能。