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

 
 
 
 





posted @ 2016-05-26 11:42  _Doing  阅读(337)  评论(0编辑  收藏  举报