Student类
package com.shrimpking.t10;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/6 21:17
*/
public class Student implements Comparable
{
private int no;
private String name;
public Student(int no, String name)
{
this.no = no;
this.name = name;
}
@Override
public int compareTo(Object o)
{
Student stu = (Student)o;
return this.no > stu.no ? 1 : (this.no < stu.no ? -1 : 0);
}
@Override
public String toString()
{
return "Student{" + "no=" + no + ", name='" + name + '\'' + '}';
}
}
排序
package com.shrimpking.t10;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/6 21:21
*/
public class ObjectArraySort
{
public static void main(String[] args)
{
Student[] students = new Student[3];
students[0] = new Student(3,"zhang");
students[1] = new Student(1,"wang");
students[2] = new Student(2,"li");
Arrays.sort(students);
for (Student student : students)
{
System.out.println(student);
}
}
}
Student类中的compareTo方法就是对Comparable接口的compareTo方法的实现,在方法内,我们使用了三元运算符“?:”对两个对象的学号进行比较,当然也可以使用if/else if/else语句来进行判断比较。
在对对象数组进行排序时,除了让对象实现Comparable接口外,还可以提供一个单独的比较器对象,用于指定对象间的排序规则。比较器对象是实现了Comparator接口的对象,该接口位于java.util包中,用于比较的方法是compare,该方法接受两个对象参数,判断逻辑与Comparable接口中的compareTo方法一样,当前一个对象小于、等于或者大于后一个对象时,则分别返回负整数、0或者正整数。在Comparator接口中还有一个抽象方法equals,但这个方法可以不用去实现,因为所有的类都是从Object类继承而来的,而Object类就有equals方法,相当于基类替我们实现了equals抽象方法。
Student类
package com.shrimpking.t11;
import java.util.Comparator;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/6 21:28
*/
public class Student
{
private int no;
private String name;
public Student(int no, String name)
{
this.no = no;
this.name = name;
}
@Override
public String toString()
{
return "Student{" + "no=" + no + ", name='" + name + '\'' + '}';
}
static class StudentComparator implements Comparator{
@Override
public int compare(Object o1, Object o2)
{
Student stu1 = (Student)o1;
Student stu2 = (Student)o2;
if(stu1.no > stu2.no){
return 1;
}else if(stu1.no < stu2.no){
return -1;
}else
{
return 0;
}
}
}
}
package com.shrimpking.t11;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/6 21:31
*/
public class ObjectArraySort
{
public static void main(String[] args)
{
Student[] students = new Student[3];
students[0] = new Student(3,"zhang");
students[1] = new Student(1,"wang");
students[2] = new Student(2,"li");
Arrays.sort(students,new Student.StudentComparator());
for (Student student : students)
{
System.out.println(student);
}
}
}