1.创建比较规则的类,让此类实现Compare接口
2.重写compare(Object o1 ,Object o2);
3.在方法内制定比较规则
4.创建比较规则对象
5.该对象调用 比较方法 根据放回值 确定哪一个对象大
>0 :前一个对象 >后一个对象
<0 :前一个对象 <后一个对象
==0 :前一个对象 ==后一个对象
按照id比
第一步:创建比较规则的类,让此类实现Compare接口
第二步:重写compare(Object o1 ,Object o2);
第三步:在方法内制定比较规则
import java.util.Comparator;
public class sortById implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Employee e1 = (Employee)o1;
Employee e2 = (Employee)o2;
return e1.id - e2.id;
}
}
第四步:创建比较规则对象
第五步:该对象调用 比较方法 根据放回值 确定哪一个对象大
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee(1, "张三", 999.9);
Employee e2 = new Employee(2,"李四",99.6);
/*创建比较类对象*/
sortById sortById = new sortById();
int sort = sortById.compare(e1, e2);
System.out.println(sort);
}
}
JavaBean对象:
public class Employee {
int id;
String name;
double salary;
public Employee() {
}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
数组工具类和外部比较器结合使用
按照id值进行排序
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee(1,"张三",9999.9);
Employee e2 = new Employee(6,"李四",9999.3);
Employee e3 = new Employee(3,"王五",9999.3);
Employee e4 = new Employee(4,"赵六",9999.9);
Employee e5 = new Employee(2,"陈七",9999.8);
Employee [] es = {e1,e2,e3,e4,e5};
/*创建比较类对象*/
sortById sortById = new sortById();
Arrays.sort(es, sortById);
for (Employee ele :es){
System.out.println(ele);
}
}
}