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 objectIt 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().

 
 
 
 





转载于:https://www.cnblogs.com/Doing-what-I-love/p/5530482.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值