- 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。