| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
|
Advertisement
|
What is the difference(or relation) between the Comparator and the Comparable interfaces?Classes that implement these two interfaces play different roles in the sorting process. A class that implements the Comparable interface, i.e., a Comparable type, is the type that is sorted, while a class that implements the Comparator interface, i.e., a Comparator, is used to compare other types. A Comparable object can compare itself to another Object using its compareTo(Object other) method. The object itself defines how the comparison is done. Interface Comparable<T> has a method: public int compareTo(T o) A Comparator object is used to compare two objects of the same type using the compare(Object other1, Object other2) method. When using a Comparator, the objects being compared don't need to define the rule of comparison. Interface Comparator<T> has a method: public int compare(T o1, T o2) The primary use of a Comparator is to pass it to something that does sorting, either one of the explicit sort methods, or to a data structure than implicitly sorts (e.g., TreeSet or TreeMap). ... Comparator You use Comparable if you want to implement the comparison method into the value object class itself. If you want to keep the comparison method separate from the value object class, you should use Comparator and create a separate class that implements that interface. Here are some rules of thumb:
A Comparator is a "third-party" tool used by a container to order its contents. The container will pass two objects to the supplied Comparator each time it needs to compare them. The Comparator is responsible for returning an indication of the ordering of the two objects but has no relationship with the objects other than that. The comparator object does not need to be an instance of any class related to the objects being compared, it just needs to know how to compare them. A Comparable object, on the other hand, knows how to compare itself with another supplied object. If no Comparator is specified then the container must compare its contents by asking each one how it relates to another.
|