Java-利用比较器解耦后

2021-01-03  本文已影响0人  hello_world_cxm
package Hello1;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * 需求:实现名字 年龄灵活排序,不用修改Student里的代码
 * */
public class Test11 {
    public static void main(String[] args) {
        Student[] xx = {  //定义一个对象数组
            new Student("cxm",34),
            new Student("axm",36),
            new Student("ssm",32),
            new Student("kxm",31),
        };
        //Comparator是接口,所以后面要用匿名内部类来实现Comparator所定义的方法
        //因为是比较器,所以你得告诉构造器,你要比较的对象类型是什么,所以得用泛型
        Comparator<Student> c1 = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //o1 和 o2是学生对象,
                //返回正负整数 
                return o1.age - o2.age;
            }
        };
        Comparator<Student> c2 = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.name.compareTo(o2.name);  //compareTo是Comparable的
            }
            
        };
        //根据name来实现排序
        List<Student> LL= Arrays.asList(xx);
        Collections.sort(LL,c2);
        for(Student ss: xx) {
            System.out.println(ss.toString());
        }
    }
}
class Student { 
    public String name;
    public int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + this.name + ", age=" + this.age + "]";  //this当前类
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读