1.利用Comparable接口实现(用的多)
JAVA中对象数组排序需要实现Comparable接口
该接口位于java.lang包下
public interface Comparable<T>
是一个泛型接口,包含一个方法
int compareTo(T o)
//return 负数,表示当前对象小于特定对象o
//return 0,表示当前对象等于特定对象o
//return 正数,表示当前对象大于特定对象
例如:
class Student implements Comparable<Student>{
private int ID;
private String name;
public Student(int ID,String name) {
this.ID = ID;
this.name = name;
}
public int compareTo(Student o) {
if(this.ID>o.ID) {
return 1;
}else if(this.ID<o.ID){
return -1;
}
else if(this.ID ==o.ID){
return 0;
}
return 0;
}
public String toString() {
return "Student [ID=" + ID + ", name=" + name + "]\n";
}
}
public class Run {
public static void main(String[] args) {
Student [] stu = new Student [] {
new Student(123,"王老吉"),
new Student(126,"加多宝"),
new Student(125,"哇哈哈")};
Arrays.sort(stu); //对Student数组进行排序
System.out.println(Arrays.toString(stu));//关于toString方法可以参考源码
}
}
输出:
[Student [ID=123, name=王老吉]
, Student [ID=125, name=哇哈哈]
, Student [ID=126, name=加多宝]
]
结果按ID升序排列,如果想按降序排列,将compareTo方法里面正负数对调即可。
2.利用Comparator接口实现(使用不多)
java.util包下的Comparator接口
@FuntionalInterface
public interface Comparator<T>
该接口有许多静态方法与普通方法
抽象方法:
int compare(T o1, T o2)
return 正数表示o1>o2,
return 负数表示o1
//比较的定义
class StudentCompare implements Comparator<Student>{
public int compare(Student o1, Student o2) {
if(o1.getID()>o2.getID()) {
return 1;
}else if(o1.getID()<o2.getID()) {
return -1;
}
return 0;
}
}
class Student {
private int ID;
private String name;
public Student(int ID,String name) {
this.ID = ID;
this.name = name;
}
public int getID() {
return this.ID;
}
public String toString() {
return "Student [ID=" + ID + ", name=" + name + "]\n";
}
}
public class Run {
public static void main(String[] args) {
Student [] stu = new Student [] {
new Student(123,"王老吉"),
new Student(126,"加多宝"),
new Student(125,"哇哈哈")};
//调用的还是Arrays的方法,这里也可以用Lambda表达式来写比较规则
Arrays.sort(stu,new StudentCompare());
System.out.println(Arrays.toString(stu));
}
}
输出:
[Student [ID=123, name=王老吉]
, Student [ID=125, name=哇哈哈]
, Student [ID=126, name=加多宝]
]