容易遗忘的Comparable:一个结果集List,里面有很多的对象,要求根据对象的指定(age)字段进行排序
来源:互联网 发布:翻译软件app排行榜 编辑:程序博客网 时间:2024/06/06 14:22
要排序的User bean要实现Comparable接口,重写 compareTo方法,面试过程中被问到的时候很可能会思考短路哦 package com.jiaocaigen; import java.util.*; public class SortTest { public static void main(String[] args) { List<User> c = new ArrayList(); c.add( new User(10, "zs1" )); c.add( new User(20, "zsxy" )); c.add( new User(20, "zs2" )); c.add( new User(40, "zs4" )); c.add( new User(30, "zs3" )); c.add( new User(50, "zs5" )); // 正序 Collections.sort((List<User>) c); // 逆序:只需先正序再翻转 // Collections.reverse((List<User>) c); System. out .println(c); } } /** * * 需要排序的 bean 对象 * * 用例是这样的 * 一个结果集 List ,里面有很多的对象,要求根据对象的 age 字段进行排序。 * @author 雷伟 2011 - 9 - 11 */ class User implements Comparable{ private int age ; private String name ; public User() { super (); } public User( int age, String name) { super (); this . age = age; this . name = name; } public int getAge() { return age ; } public void setAge( int age) { this . age = age; } public String getName() { return name ; } public void setName(String name) { this . name = name; } /* * 按照 id 从小到大的顺序排序。 自己可以在方法里面编写任意的排序算法。 */ public int compareTo(Object o) { User user = (User) o; // 根据 ID 从小到大顺序。 if ( this . age > user.getAge()){ return 1; } else if ( this . age < user.getAge()){ return -1; } else { return 0; } } // 重写 toString 方法 public String toString() { return this . age + " " + this . name ; } }