您好,登錄后才能下訂單哦!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- public class fuxi6_compare
- {
- public static void main(String[] args)
- {
- ArrayList<Students> list = new ArrayList<Students>();
- list.add(new Students("acc", 28));
- list.add(new Students("aa", 20));
- list.add(new Students("ddd", 25));
- list.add(new Students("eee", 22));
- list.add(new Students("fff", 26));
- list.add(new Students("ggg", 23));
- Collections.sort(list); //直接對students對象排序
- Caipan caipan = new Caipan(); //創建裁判對象
- Collections.sort(list,caipan); //根據裁判來排序
- System.out.println(list);
- }
- }
- /**
- *
- *直接實現比較接口,重寫compareTo方法
- */
- class Students implements Comparable<Students> //記得添加泛型
- {
- String name;
- int age;
- public Students(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- @Override
- public int compareTo(Students o) //重寫compareTo,返回值負數、0、正數判斷大小
- {
- return o.age - this.age; //由大到小排列
- }
- /**
- * 名字按字母順序排列,直接調用compareTo方法比較即可
- */
- // @Override
- // public int compareTo(Person o)
- // {
- // return this.name.compareTo(o.name);
- // }
- @Override
- public String toString()
- {
- return "Students [name=" + name + ", age=" + age + "]";
- }
- }
- /**
- * 創建一個裁判來進行比較,裁判需要實現Comparator
- */
- class Caipan implements Comparator<Students>//必須添加泛型
- {
- @Override
- public int compare(Students stu1, Students stu2)
- {
- return stu1.age - stu2.age;
- }
- }
- class Students
- {
- String name;
- int age;
- public Students(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- @Override
- public String toString()
- {
- return "Students [name=" + name + ", age=" + age + "]";
- }
- }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。