//通过两种比较器排序
//比较器
//
//Comparable:自然排序使用
// 规则:
// this属性 参数对象o属性 比较
// this > o 正数
// this < o 负数
// this == o 0
//
//Comparator:外部比较器
//
//
//
//--------------------------------------
//Comparable 和 Comparator区别:
//1.位置。
// Comparable 代码写在要比较的类中;
// Comparator 代码写在要比较的类外;
//2.个数。
// Comparable 就定义一种;
// Comparator 可以定义多个比较方式。
import java.util.Arrays;
public class TestTel {
public static void main(String[] args) {
Mumber[] mum = new Mumber[3];
Mumber m1 = new Mumber("001", "张三", 500);
Mumber m2 = new Mumber("010", "李四", 1100);
Mumber m3 = new Mumber("006", "王五", 200);
mum[0] = m1;
mum[1] = m2;
mum[2] = m3;
//第一种Comparable 外部比较器
Arrays.sort(mum);
for(Mumber s :mum) {
System.out.println(s);
}
}
}
class Mumber implements Comparable<Mumber>{
private String no;
private String name;
private int num;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Mumber(String no, String name, int num) {
super();
this.no = no;
this.name = name;
this.num = num;
}
@Override
public int compareTo(Mumber o) {
// TODO Auto-generated method stub
return o.num-this.num;
}
@Override
public String toString() {
return "Student [no=" + no + ", name=" + name + ", num=" + num+"]";
}
}
package day13;
import java.util.Arrays;
import java.util.Comparator;
class Employee{
private String name;
private int age;
public Employee(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + "]";
}
}
public class TestSort2 {
public static void main(String[] args) {
Employee guojing = new Employee("yangkang", 22);
Employee yangkang = new Employee("guojing", 20);
Employee huangrong = new Employee("huangrong", 21);
Employee [] emps = {guojing,yangkang,huangrong};
Arrays.sort(emps, new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
/* if(o1.getName().compareTo(o2.getName()) > 0) {
return 1;
}else if(o1.getName().compareTo(o2.getName()) < 0) {
return -1;
}else {
if(o1.getAge() > o2.getAge() ) {
return 1;
}else if(o1.getAge() < o2.getAge()) {
return -1;
}else {
return 0;
}
}*/
if(o1.getName().compareTo(o2.getName()) == 0) {
return o1.getAge() - o2.getAge();
}
return o1.getName().compareTo(o2.getName());
}
});
for(Employee emp : emps) {
System.out.println(emp);
}
}
}