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