普通情况下在实现对对象元素的数组或集合进行排序的时候会用到Comparator和Comparable接口,通过在元素所在的类中实现这两个接口中的一个。然后对数组或集合调用Arrays.sort或者Collentions.sort方法就可以实现对数组或集合的排序。就sort方法里面的參数来说。实现了不同的接口则传递的參数也不尽同样。对于实现了Comparator接口的类来说。sort方法须要接受的參数不仅包含数组或集合。还要包含实现了该接口的类对象。而对实现了Comparable接口的类来说,參数不仅包含数组或者集合,还要包含实现了该接口的类对象。

详细怎么差别呢,事实上非常easy,由于看两个接口所实现的方法就知道,Comparator定义的方法为compare(Object o1, Object o2)。方法涉及两个类对象。所以须要在另外一个新的类来实现对数组元素的比較,所以在调用sort方法时须要传递这个额外的实现了Comparator接口的类对象;而实现了Comparable接口的类实在元素类的内部实现了排序的逻辑,所以调用sort方法时不须要传递额外的类对象。废话少说,直接上代码。

1.通过实现Comparator接口来实现对数组或集合的比較

  1. class SortCat implements Comparator<Cat1>
  2. {
  3. @Override
  4. public int compare(Cat1 o1, Cat1 o2)//实现了Comparator接口的compare方法
  5. {
  6. // TODO Auto-generated method stub
  7. int size1=o1.getSize(),size2=o2.getSize();
  8. if(size1!=size2)
  9. return size1-size2;
  10. return o1.getColor().compareTo(o2.getColor());
  11. }
  12. }
  13. class Cat1
  14. {
  15. private String color;
  16. private int size;
  17. public Cat1(String color,int size)
  18. {
  19. this.color=color;
  20. this.size=size;
  21. }
  22. public int getSize()
  23. {
  24. return size;
  25. }
  26. public String getColor()
  27. {
  28. return color;
  29. }
  30. public String toString()
  31. {
  32. return color+" cat,size = "+size;
  33. }
  34. }
  35. public class HashMapComparatorDemo
  36. {
  37. public static void main(String[] args)
  38. {
  39. // TODO Auto-generated method stub
  40. String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
  41. int catSizeArr[]={5,3,7,9,6,4,1,8,2};
  42. Random random=new Random();
  43. Cat1 catArr[]=new Cat1[10];
  44. int sizeIndex=0,colorIndex=0;
  45. for(int i=0;i<10;i++)
  46. {
  47. sizeIndex=random.nextInt(catSizeArr.length);
  48. colorIndex=random.nextInt(colorArr.length);
  49. catArr[i]=new Cat1(colorArr[colorIndex], catSizeArr[sizeIndex]);
  50. System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
  51. }
  52. System.out.println("\nAfter change the order....\n");
  53. Arrays.sort(catArr,new SortCat());//不仅要传递数组參数。还要传递实现了Comparator接口的类对象
  54. for(Cat1 cat:catArr)
  55. System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize());
  56. }
  57. }

结果:

  1. Color:white,size:4
  2. Color:colorful,size:4
  3. Color:colorful,size:4
  4. Color:gray,size:5
  5. Color:yellow,size:7
  6. Color:orange,size:6
  7. Color:black,size:2
  8. Color:colorful,size:8
  9. Color:black,size:3
  10. Color:yellow,size:2
  11. After change the order....
  12. Color:black,size:2
  13. Color:yellow,size:2
  14. Color:black,size:3
  15. Color:colorful,size:4
  16. Color:colorful,size:4
  17. Color:white,size:4
  18. Color:gray,size:5
  19. Color:orange,size:6
  20. Color:yellow,size:7
  21. Color:colorful,size:8

2.通过实现Comparable接口来实现对数组或集合的比較

  1. class Cat2 implements Comparable<Cat2>
  2. {
  3. private String color;
  4. private int size;
  5. public Cat2(String color,int size)
  6. {
  7. this.color=color;
  8. this.size=size;
  9. }
  10. public int getSize()
  11. {
  12. return size;
  13. }
  14. public String getColor()
  15. {
  16. return color;
  17. }
  18. public String toString()
  19. {
  20. return color+" cat,size = "+size;
  21. }
  22. @Override
  23. public int compareTo(Cat2 o)//在元素类里面实现comparable接口所定义的方法
  24. {
  25. // TODO Auto-generated method stub
  26. int size=o.getSize();
  27. if(this.size!=size)
  28. return this.size-size;
  29. return this.color.compareTo(o.getColor());
  30. }
  31. }
  32. public class HashMapComparatorDemo2
  33. {
  34. public static void main(String[] args)
  35. {
  36. String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
  37. int catSizeArr[]={5,3,7,9,6,4,1,8,2};
  38. Random random=new Random();
  39. Cat2 catArr[]=new Cat2[10];
  40. int sizeIndex=0,colorIndex=0;
  41. for(int i=0;i<10;i++)
  42. {
  43. sizeIndex=random.nextInt(catSizeArr.length);
  44. colorIndex=random.nextInt(colorArr.length);
  45. catArr[i]=new Cat2(colorArr[colorIndex], catSizeArr[sizeIndex]);
  46. System.out.println("Color:"+catArr[i].getColor()+",size:"+catArr[i].getSize());
  47. }
  48. System.out.println("\nAfter change the order....\n");
  49. Arrays.sort(catArr);//仅须要传递数组或集合就可以
  50. for(Cat2 cat:catArr)
  51. System.out.println("Color:"+cat.getColor()+",size:"+cat.getSize());
  52. }
  53. }

结果:

  1. Color:gray,size:7
  2. Color:orange,size:9
  3. Color:gray,size:3
  4. Color:brown,size:5
  5. Color:orange,size:1
  6. Color:gray,size:8
  7. Color:colorful,size:9
  8. Color:white,size:1
  9. Color:blue,size:7
  10. Color:brown,size:1
  11. After change the order....
  12. Color:brown,size:1
  13. Color:orange,size:1
  14. Color:white,size:1
  15. Color:gray,size:3
  16. Color:brown,size:5
  17. Color:blue,size:7
  18. Color:gray,size:7
  19. Color:gray,size:8
  20. Color:colorful,size:9
  21. Color:orange,size:9

3.另外。还能够用实现了对Comparable接口treeMap、treeSet进行排序,详细应用范围非常广。包含求一个无反复无序数组的前k项元素就能够用treeSet或treeMap非常好滴实现,循环建tree并维持一个大小为k的treeSet或treeMap就可以。超出范围的话先插入一个元素。然后删除排在最后的元素就可以。以下这段代码只实现的是有序建树并将treeMap输出出来的功能。

  1. class Cat implements Comparable<Cat>
  2. {
  3. private String color;
  4. private int size;
  5. public Cat(String color,int size)
  6. {
  7. this.color=color;
  8. this.size=size;
  9. }
  10. public int getSize()
  11. {
  12. return size;
  13. }
  14. public String getColor()
  15. {
  16. return color;
  17. }
  18. @Override
  19. public int compareTo(Cat o)
  20. {
  21. // //优先依据颜色排序
  22. // String color1=o.getColor();
  23. // if(this.color.compareTo(color1)!=0)
  24. // return this.color.compareTo(color1);
  25. // return this.size-o.size;
  26. //优先依据大小排序
  27. int size=o.getSize();
  28. if(this.size!=size)
  29. return this.size-size;
  30. return this.color.compareTo(o.getColor());
  31. }
  32. public String toString()
  33. {
  34. return "Color:"+color+",size = "+size;
  35. }
  36. }
  37. public class HashMapComparableDemo
  38. {
  39. public static void main(String[] args)
  40. {
  41. SortedMap<Cat, Integer>map=new TreeMap();
  42. String colorArr[]={"black","yellow","white","colorful","gray","brown","blue","orange"};
  43. int catSizeArr[]={5,3,7,9,6,4,1,8,2};
  44. Random random=new Random();
  45. int sizeIndex=0,colorIndex=0,count=0;;
  46. int mapSize=10;
  47. for(int i=0;i<mapSize;i++)
  48. {
  49. sizeIndex=random.nextInt(catSizeArr.length);
  50. colorIndex=random.nextInt(colorArr.length);
  51. count=random.nextInt(20)+5;
  52. map.put(new Cat(colorArr[colorIndex], catSizeArr[sizeIndex]), count);
  53. }
  54. Iterator<Entry<Cat, Integer>>iterator=map.entrySet().iterator();
  55. Entry<Cat, Integer>entry;
  56. while(iterator.hasNext())
  57. {
  58. entry=iterator.next();
  59. System.out.println(entry.getKey().toString()+",Count:"+entry.getValue().toString());
  60. }
  61. }
  62. }

结果:

  1. Color:black,size = 1,Count:15
  2. Color:black,size = 2,Count:12
  3. Color:gray,size = 2,Count:24
  4. Color:brown,size = 5,Count:24
  5. Color:gray,size = 5,Count:14
  6. Color:brown,size = 6,Count:13
  7. Color:white,size = 6,Count:7
  8. Color:yellow,size = 6,Count:12
  9. Color:gray,size = 7,Count:9
  10. Color:brown,size = 8,Count:17

另外:对某些对象建立treeMap或hashMap的时候还须要重写一下equals方法,防止发生插入同样元素的情况,由于默认情况下treeMap或HashMap是应该是以对象的引用作为各个对象元素的标志。而不是元素的值。

Java中Comparator接口和Comparable接口的使用的更多相关文章

  1. java中的类实现comparable接口 用于排序

    import java.util.Arrays; public class SortApp { public static void main(String[] args) { Student[] s ...

  2. Java中 Comparator接口 与Comparable 的区别

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt159 comparator接口与Comparable接口的区别 1. Com ...

  3. 在java中,List是个接口,那实现List接口的类有哪些,有什么区别?

    在java中,List是个接口,那实现List接口的类有哪些,有什么区别? 解答: ArrayList是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引 ...

  4. 如何理解 Java 中的 <T extends Comparable<? super T>>

    Java 中类似 <T extends Comparable<? super T>> 这样的类型参数 (Type Parameter) 在 JDK 中或工具类方法中经常能看到. ...

  5. Java Comparator方法 和 Comparable接口

    默认的排序方法: 让类继承Comparable接口,重写compareTo方法. 示例代码: package com.imooc.collection; import java.util.HashSe ...

  6. Java 之 比较器( Comparator接口与 Comparable 接口)

    一.定制排序:java.util.Comparator 接口 强行对某个对象 collection 进行整体排序 的比较函数.可以将 Comparator 传递给 sort 方法(如 Collecti ...

  7. Java中的TreeMap、Comparable、Comparator

    我们知道HashMap的存储位置是按照key这个对象的hashCode来存放的,而TreeMap则是不是按照hashCode来存放,他是按照实现的Comparable接口的compareTo这个方法来 ...

  8. 关于comparator接口和comparable接口以及它们各自的方法compare()和compareTo()

    在今天做的LeetCode的题中有两道都出现了利用接口实现对象的排序.两题的相关链接: 1.利用comparable接口对对象排序 2.利用comparator接口实现排序 因为之前都没接触过这两个接 ...

  9. 实现Comparator接口和Comparable接口,以及Map按value排序 ,map遍历

    继承Comparator接口,重写compare()方法 import java.util.ArrayList; import java.util.Arrays; import java.util.C ...

随机推荐

  1. iTOP-6818开发板设置NFS共享目录的实现

    NFS 共享目录的制作过程.主要分为两个步骤:1.搭建 NFS 服务器2.配置内核. NFS 是 Network FileSystem 的缩写,是由 SUN 公司研制的 UNIX 表示层协议(pres ...

  2. OpenCV2:应用篇 QT+OpenCV实现图片编辑器

    一.简介 做完会放在Github上  

  3. 第4节 hive调优:1、2、fetch抓取和表的优化

    hive的调优:第一个调优:fetch抓取,能够避免使用mr的,就尽量不要用mr,因为mr太慢了 set hive.fetch.task.conversion=more 表示我们的全局查找,字段查找, ...

  4. Git中文书籍

    Git中文书籍: http://git-scm.com/book/zh/v1

  5. swiper实现响应式全屏自动轮播

    html: <!--轮播 --> <div class="Excellent_swi"> <div class="swiper-contai ...

  6. 笔试算法题(14):整数二进制表示中的1 & 判定栈的push和pop序列是否对应

    出题:输入一个整数,要求计算此整数的二进制表示中1的个数 分析: 如果整数表示为k,当其是负数的时候,使用1<<i分别检测k的每一位:当其位整数的时候,则k/2表示将其二进制表示右移一位, ...

  7. [Python3网络爬虫开发实战] 1.3.3-pyquery的安装

    pyquery同样是一个强大的网页解析工具,它提供了和jQuery类似的语法来解析HTML文档,支持CSS选择器,使用非常方便.本节中,我们就来了解一下它的安装方式. 1. 相关链接 GitHub:h ...

  8. impdp导入

    //导入命令impdp 用户/密码@数据库链接 directory=数据库中映射路径 schemas=原用户 remap_schema=原用户:现用户 remap_tablespace=原表空间:现表 ...

  9. 第二次 Ubuntu16.04 vi编辑器的方向键和退格问题

    新安装ubuntu后,好多人可能都碰到过这样的问题,vi对文件进行编辑时,上下左右键变成了ABDC,退格键也不管用. 解决办法其实也很简单,首先卸载掉旧的vim-common. apt-get rem ...

  10. Python之面向对象slots与迭代器协议

    Python之面向对象slots与迭代器协议 slots: # class People: # x=1 # def __init__(self,name): # self.name=name # de ...