一、Comparable接口的使用
需比较的对象实现Comparable接口,重写public int compareTo(Object other){} 即可
import java.util.ArrayList;
import java.util.Collections;public class TestComparable{
public static void main(String[] args){
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(4));
students.add(new Student(2));
students.add(new Student(1));
students.add(new Student(9));
Collections.sort(students); //按照我们重写的规定排序
System.out.println(students.toString());
for(Student student:students){
System.out.println(student);
}
}
}
//使用泛型
class Student implements Comparable<Student>{
private int id;
public Student(int id){
this.id = id;
}
public int compareTo(Student other){
//Student o = (Student)other;
if(this.id>other.id){
return 1;
}else if(this.id<other.id){
return -1;
}else{
return 0;
}
}
public String toString(){
return "student id = " + id;
}
}
//未使用泛型
/*
private int id;
public Student(int id){
this.id = id;
}
public int compareTo( Object other){//形参必须为Object
Student o = (Student)other;
if(this.id>o.id){ //当前对象与形参对象比较,大于零就是升序,小于零降序
return 1;
}else if(this.id<o.id){
return -1;
}else{
return 0;
}
}
public String toString(){
return "student id = " + id;
}
}
*/
输出结果:
[student id = 1, student id = 2, student id = 4, student id = 9]
student id = 1
student id = 2
student id = 4
student id = 9
二、Comparator接口的使用
需比较的对象实现Comparator接口,重写public int compare(Object o1,Object o2){} 即可
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestComparator {
public static void main(String[] args){
ArrayList<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(5));
emps.add(new Emp(1));
emps.add(new Emp(78));
emps.add(new Emp(3));
emps.add(new Emp(13));
Collections.sort(emps,new Emp()); //按照我们重写的规定排序
System.out.println(emps.toString());
for(Emp emp:emps){
System.out.println(emp);
}
}
}
class Emp implements Comparator{
private int id;
public Emp(int id){
this.id = id;
}
public Emp(){
}
public int compare(Object o1,Object o2){
Emp emp1 = (Emp)o1;
Emp emp2 = (Emp)o2;
if(emp1.id>emp2.id){//第一个对象的成员大于第二个返回1时升序
return 1;
}else if(emp1.id<emp2.id){
return -1;
}else{
return 0;
}
}
public String toString(){
return "emp id = " + this.id;
}
}
输出结果:
[emp id = 1, emp id = 3, emp id = 5, emp id = 13, emp id = 78]
emp id = 1
emp id = 3
emp id = 5
emp id = 13
emp id = 78