1,创建一个实体类对象,并且实现Comparable 接口

public class Book implements Comparable {public int id;// 编号 public String name;// 名称 public double price; // 价格 private String author;// 作者 public GregorianCalendar calendar;// 出版日期 public Book() { this(0, "X", 0.0, new GregorianCalendar(), ""); } public Book(int id, String name, double price, GregorianCalendar calender, String author) { this.id = id; this.name = name; this.price = price; this.calendar = calender; this.author = author; }@Overridepublic int compareTo(Object obj) {Book b = (Book) obj; return this.id - b.id; // 按书的id比较大小,用于默认排序 } },

2,创建对象,添加到集合中,再排序,打印出来。

public class UseCompartor {public static void main(String args[]) { List<Book> list = new ArrayList<Book>(); // 数组序列 Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009, 01, 25), "曹雪芹、高鄂"); Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7, 8), "罗贯中 "); Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6, 28), "施耐庵 "); Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6, 8), "吴承恩"); Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9, 23), "搜狐"); list.add(b1); list.add(b2); list.add(b3); list.add(b4); list.add(b5); // Collections.sort(list); //没有默认比较器,不能排序 System.out.println("数组序列中的元素:"); myprint(list); Collections.sort(list, new PriceComparator()); // 根据价格排序 System.out.println("按书的价格排序:"); myprint(list); Collections.sort(list, new CalendarComparator()); // 根据时间排序 //把顺序颠倒下Collections.reverse(list);System.out.println("按书的出版时间排序:"); myprint(list); } // 自定义方法:分行打印输出list中的元素 public static void myprint(List<Book> list) { Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素 while (it.hasNext()) {// 如果迭代器中有元素,则返回true System.out.println("\t" + it.next());// 显示该元素 } } // 自定义比较器:按书的价格排序 static class PriceComparator implements Comparator { public int compare(Object object1, Object object2) {// 实现接口中的方法 Book p1 = (Book) object1; // 强制转换 Book p2 = (Book) object2; return new Double(p1.price).compareTo(new Double(p2.price)); } } // 自定义比较器:按书出版时间来排序 static class CalendarComparator implements Comparator { public int compare(Object object1, Object object2) {// 实现接口中的方法 Book p1 = (Book) object1; // 强制转换 Book p2 = (Book) object2; return p2.calendar.compareTo(p1.calendar); } } }

更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. Python list sort方法的具体使用
  3. python list.sort()根据多个关键字排序的方法实现
  4. android上一些方法的区别和用法的注意事项
  5. Android开发者实用代码片段 与大家分享
  6. [android]在上下文菜单的选中事件中获取列表选中的元素
  7. android上一些方法的区别和用法的注意事项
  8. Android(安卓)实现View中添加子元素的动态效果
  9. Android(安卓)通讯录中用到的关于按名字首字母排序方法

随机推荐

  1. google nexus 10 用fastboot 刷机教程 (官
  2. android eclipse基础开发环境搭建(最新安
  3. Android(安卓)Jetpack架构组件 — Naviga
  4. Nexus S不能发短信的解决方法
  5. OpenGL ES 系列教程
  6. Android(安卓)开发艺术探索之---ContentP
  7. [Android(安卓)性能优化系列]内存之终极
  8. BAT大咖助力 全面升级Android面试-3andro
  9. LiveData+ViewModel+Lifecycle
  10. Android(安卓)10.0文件存储问题