Comparator是个接口,可重写compare()及equals()这两个方法,用于比价功能;如果是null的话,就是使用元素的默认顺序,如a,b,c,d,e,f,g,就是a,b,c,d,e,f,g这样,当然数字也是这样的。
compare(a,b)方法:根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数。
equals(obj)方法:仅当指定的对象也是一个 Comparator,并且强行实施与此 Comparator 相同的排序时才返回 true。

Collections.sort(list, new PriceComparator());的第二个参数返回一个int型的值,就相当于一个标志,告诉sort方法按什么顺序来对list进行排序。

具体实现代码方法如下:

Book实体类:

  1. package com.tjcyjd.comparator;
  2. import java.text.DecimalFormat;
  3. import java.text.SimpleDateFormat;
  4. import java.util.GregorianCalendar;
  5. import java.util.Iterator;
  6. import java.util.TreeMap;
  7. /**
  8. * 书实体类
  9. *
  10. * @author yjd
  11. *
  12. */
  13. public class Book implements Comparable { // 定义名为Book的类,默认继承自Object类
  14. public int id;// 编号
  15. public String name;// 名称
  16. public double price; // 价格
  17. private String author;// 作者
  18. public GregorianCalendar calendar;// 出版日期
  19. public Book() {
  20. this(0, "X", 0.0, new GregorianCalendar(), "");
  21. }
  22. public Book(int id, String name, double price, GregorianCalendar calender,
  23. String author) {
  24. this.id = id;
  25. this.name = name;
  26. this.price = price;
  27. this.calendar = calender;
  28. this.author = author;
  29. }
  30. // 重写继承自父类Object的方法,满足Book类信息描述的要求
  31. public String toString() {
  32. String showStr = id + "\t" + name; // 定义显示类信息的字符串
  33. DecimalFormat formatPrice = new DecimalFormat("0.00");// 格式化价格到小数点后两位
  34. showStr += "\t" + formatPrice.format(price);// 格式化价格
  35. showStr += "\t" + author;
  36. SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日");
  37. showStr += "\t" + formatDate.format(calendar.getTime()); // 格式化时间
  38. return showStr; // 返回类信息字符串
  39. }
  40. public int compareTo(Object obj) {// Comparable接口中的方法
  41. Book b = (Book) obj;
  42. return this.id - b.id; // 按书的id比较大小,用于默认排序
  43. }
  44. public static void main(String[] args) {
  45. Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009,
  46. 01, 25), "曹雪芹、高鄂");
  47. Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7,
  48. 8), "罗贯中 ");
  49. Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6,
  50. 28), "施耐庵 ");
  51. Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6,
  52. 8), "吴承恩");
  53. Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9,
  54. 23), "搜狐");
  55. TreeMap tm = new TreeMap();
  56. tm.put(b1, new Integer(255));
  57. tm.put(b2, new Integer(122));
  58. tm.put(b3, new Integer(688));
  59. tm.put(b4, new Integer(453));
  60. tm.put(b5, new Integer(40));
  61. Iterator it = tm.keySet().iterator();
  62. Object key = null, value = null;
  63. Book bb = null;
  64. while (it.hasNext()) {
  65. key = it.next();
  66. bb = (Book) key;
  67. value = tm.get(key);
  68. System.out.println(bb.toString() + "\t库存:" + tm.get(key));
  69. }
  70. }
  71. }

自定义比较器和测试类:

    1. package com.tjcyjd.comparator;
    2. import java.util.ArrayList;
    3. import java.util.Collections;
    4. import java.util.Comparator;
    5. import java.util.GregorianCalendar;
    6. import java.util.Iterator;
    7. import java.util.List;
    8. public class UseComparator {
    9. public static void main(String args[]) {
    10. List<Book> list = new ArrayList<Book>(); // 数组序列
    11. Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009,
    12. 01, 25), "曹雪芹、高鄂");
    13. Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7,
    14. 8), "罗贯中 ");
    15. Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6,
    16. 28), "施耐庵 ");
    17. Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6,
    18. 8), "吴承恩");
    19. Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9,
    20. 23), "搜狐");
    21. list.add(b1);
    22. list.add(b2);
    23. list.add(b3);
    24. list.add(b4);
    25. list.add(b5);
    26. // Collections.sort(list); //没有默认比较器,不能排序
    27. System.out.println("数组序列中的元素:");
    28. myprint(list);
    29. Collections.sort(list, new PriceComparator()); // 根据价格排序
    30. System.out.println("按书的价格排序:");
    31. myprint(list);
    32. Collections.sort(list, new CalendarComparator()); // 根据时间排序
    33. System.out.println("按书的出版时间排序:");
    34. myprint(list);
    35. }
    36. // 自定义方法:分行打印输出list中的元素
    37. public static void myprint(List<Book> list) {
    38. Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素
    39. while (it.hasNext()) {// 如果迭代器中有元素,则返回true
    40. System.out.println("\t" + it.next());// 显示该元素
    41. }
    42. }
    43. // 自定义比较器:按书的价格排序
    44. static class PriceComparator implements Comparator {
    45. public int compare(Object object1, Object object2) {// 实现接口中的方法
    46. Book p1 = (Book) object1; // 强制转换
    47. Book p2 = (Book) object2;
    48. return new Double(p1.price).compareTo(new Double(p2.price));
    49. }
    50. }
    51. // 自定义比较器:按书出版时间来排序
    52. static class CalendarComparator implements Comparator {
    53. public int compare(Object object1, Object object2) {// 实现接口中的方法
    54. Book p1 = (Book) object1; // 强制转换
    55. Book p2 = (Book) object2;
    56. return p2.calendar.compareTo(p1.calendar);
    57. }
    58. }
    59. }

[转]java中Collections.sort排序详解的更多相关文章

  1. java中Collections.sort排序详解

    Comparator是个接口,可重写compare()及equals()这两个方法,用于比价功能:如果是null的话,就是使用元素的默认顺序,如a,b,c,d,e,f,g,就是a,b,c,d,e,f, ...

  2. (网页)java中Collections.sort排序详解(转)

    转自CSDN: Comparator是个接口,可重写compare()及equals()这两个方法,用于比价功能:如果是null的话,就是使用元素的默认顺序,如a,b,c,d,e,f,g,就是a,b, ...

  3. Java中Collections.sort()排序详解

      public static void main(String[] args) { List<String> list = new ArrayList<String>(); ...

  4. java中的io系统详解 - ilibaba的专栏 - 博客频道 - CSDN.NET

    java中的io系统详解 - ilibaba的专栏 - 博客频道 - CSDN.NET 亲,“社区之星”已经一周岁了!      社区福利快来领取免费参加MDCC大会机会哦    Tag功能介绍—我们 ...

  5. Java中的main()方法详解

    在Java中,main()方法是Java应用程序的入口方法,也就是说,程序在运行的时候,第一个执行的方法就是main()方法,这个方法和其他的方法有很大的不同,比如方法的名字必须是main,方法必须是 ...

  6. Java I/O : Java中的进制详解

    作者:李强强 上一篇,泥瓦匠基础地讲了下Java I/O : Bit Operation 位运算.这一讲,泥瓦匠带你走进Java中的进制详解. 一.引子 在Java世界里,99%的工作都是处理这高层. ...

  7. 关于Java中Collections.sort和Arrays.sort的稳定性问题

    一 问题的提出   关于Java中Collections.sort和Arrays.sort的使用,需要注意的是,在本文中,比较的只有Collections.sort(List<T> ele ...

  8. java中Collections.sort()方法实现集合排序

    1.Integer/String泛型的List进行排序 List <Integer> integerlist = new ArrayList<Integer>();   //定 ...

  9. java中list和map详解

    一.概叙 List , Set, Map都是接口,前两个继承至Collection接口,Map为独立接口, List下有ArrayList,Vector,LinkedList Set下有HashSet ...

随机推荐

  1. 2017 WebStorm 激活码 更新 Pycharm同样可用

    [有效时间到2017 年 11月 23日] BIG3CLIK6F-eyJsaWNlbnNlSWQiOiJCSUczQ0xJSzZGIiwibGljZW5zZWVOYW1lIjoibGFuIHl1Iiw ...

  2. PHP数据库类

    简单封装PHP操作MySQL的类 <?php /* 类的名称:Model 类的作用:连接数据库执行sql语句 作 者:lim 更新时间:20170812 */ class Model{ //存放 ...

  3. curl: (6) Couldn’t resolve host ‘www.ttlsa.com’【转】

    上周, 部分站点出现Couldn't resolve host.....问题,  导致公司所有走api的程序都无法正常使用(系统redhat 6.3的都出现问题, redhat 5一切OK). 最后解 ...

  4. sicily 1003. Hit or Miss

    Description One very simple type of solitaire game known as "Hit or Miss" (also known as & ...

  5. Oracle创建WM_CONCAT函数

    Oracle创建WM_CONCAT函数 WM_CONCAT这个函数会出错,所以从 11g开始.官方不认可 WM_CONCAT.然后就没这个函数了, 下面就是创建WM_CONCAT这个函数的步骤 第一步 ...

  6. C++卷积神经网络实例(一)

    跟着这位博主来学习C++的卷积网络实例,因为作者一直在更新代码,所以新的代码和这位博主的分析有所不同:这位博主写的东西太泛了,没有讲到实质, 可以参考下他分析的类与类之间的关系图.. 前四节:http ...

  7. HTML+CSS小技巧

    网页标题前引入ico图标 <link rel="shortcut icon" href="img/icoTest.ico">

  8. 洛谷P1720 月落乌啼算钱 题解

    题目传送门 初看题目,好难.再看一次,探索规律,发现这就是有名的斐波那契数列. F[i]=f[i-1]+f[i-2] SO 代码很简单,貌似要开long long,又貌似不用开. #include&l ...

  9. 【LOJ】#2351. 「JOI 2017/2018 决赛」毒蛇越狱

    题解 没啥特别好的算法,是个讨论题,由于0 1 ?三类数位中最少的不会超过6 如果1不超过6,那么记录\(f1(S)\)为 \(\sum_{T \subset S} val(T)\)这个可以通过类似F ...

  10. Java 中如何计算两个字符串时间之间的时间差?(单位为分钟)

    Java 中如何计算两个字符串时间之间的时间差?(单位为分钟) import java.text.DateFormat; import java.text.ParseException; import ...