Similarities:
Both are custom ways to compare two objects.
Both return an int describing the relationship between two objects.

Differences:

  • Comparator

compare() is from the Comparator interface.

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances.

The typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following:

  • Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
  • System class To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
  • Strategy pattern To implement a Strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.
Comparator comp =newMyComparator();
int result = comp.compare(object1, object2);
  • Comparable 

compareTo() is from the Comparable interface.

A comparable object is capable of comparing itself with another object. It allows an object to be compared to objects of similar type.

If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).

String s ="hi";
int result = s.compareTo("bye");

If your class objects have one natural sorting order, you may not need compare() but compareTo().

 
 
 
 

最新文章

  1. SRS(simple-rtmp-server)
  2. C# 动态修改dll的签名 以及修改引用该dll文件的签名
  3. 网络拥塞控制(三) TCP拥塞控制算法
  4. linux磁盘以及文件系统
  5. mac下的改装人生——关于mc700安装双硬盘以后的win重装问题
  6. bzoj千题计划165:bzoj5127: 数据校验
  7. 深入理解Javascript单线程谈Event Loop
  8. iOS集合视图单元格高亮和选中的区别
  9. 超实用的Docker入门教程|Docker vs VM
  10. 超简单的okHttpUtils封装(下)
  11. ADNI数据
  12. Scala中的协变,逆变,上界,下界等
  13. 廖雪峰Java1-3流程控制-9break、continue
  14. Idea 2018版破解
  15. java字节码的工具(含IDEA插件)
  16. JavaScript循环练习
  17. apache中 MaxClients 与MaxRequestsPerChild
  18. jq给动态生成的标签绑定事件的几种方法
  19. 将windows共享文件夹挂载在linux机器的/mnt/windows/ 目录下进行访问
  20. [转]hadoop2.x常用端口

热门文章

  1. ajax页面数据的传递
  2. Media Queries详解--转
  3. (转)C#Interface简介
  4. shell每日发邮件
  5. css阴影
  6. WinPcap编程(三)
  7. PHP之路——MySql查询语句
  8. zend framework 1 连接oracle数据库的写法
  9. 利用Keil u4调试,精确实现软件延时
  10. SQL server 分离数据库与删除数据库的区别