How does this comparator work?

折月煮酒 提交于 2019-12-01 22:57:20

What is a Comparable interface? It is an interface containing single method:

compareTo(T o)

providing capability for Java to comprare your object with any other. Basically you would like to compare your object with those of the same kind (class). So there is a usual check in compareTo implementation:

if (o instanceof vehicles) {
  Vehicles v = (Vehicles)o;

  // compare
} else {
  return false;
}

Then, in compare section you should decide, based on your business-rules, whether other vehicle is equals, more of less to your object.

  • 0 - if they are equal;
  • 1 - if your object is greater;
  • -1 - if your object is lesser.

All that simple!

It uses bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Check the Javadoc.

@return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Collections.sort(List list) uses this comapreTo() method to decide natural ordering of your objects. see http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!