Java-利用比較器解耦后

package Hello1;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * 需求:實現(xiàn)名字 年齡靈活排序,不用修改Student里的代碼
 * */
public class Test11 {
    public static void main(String[] args) {
        Student[] xx = {  //定義一個對象數(shù)組
            new Student("cxm",34),
            new Student("axm",36),
            new Student("ssm",32),
            new Student("kxm",31),
        };
        //Comparator是接口,所以后面要用匿名內(nèi)部類來實現(xiàn)Comparator所定義的方法
        //因為是比較器,所以你得告訴構(gòu)造器,你要比較的對象類型是什么,所以得用泛型
        Comparator<Student> c1 = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //o1 和 o2是學(xué)生對象,
                //返回正負整數(shù) 
                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的
            }
            
        };
        //根據(jù)name來實現(xiàn)排序
        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當前類
    }
    
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容