Skip to main content

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 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 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 fileComp = new FileComparator();

//... Create a File object for the current directory.
File dir = new File(".");
File[] children = dir.listFiles();

// Sort using a comparator.
Arrays.sort(children, fileComp); 
...
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:
  • If the comparison rules are simple and all the objects in the collection are of a single type, as well as you can change the code of object class. In such case, it's often easier to make them Comparable and let the container do the comparing.
  • If the comparison rules are complex and/or objects in the collection are a wide variety of object types, it makes more sense to build an external Comparator interface.
  • Sometime, implementing Comparator is the only option because you can't change the code of the object. But you still want to sort these objects in a Collection. You can create a Comparator that will take two objects and compare based on your own criteria, then pass that into the Sorted Collection, or using the Collections.sort() method to sort based on your way of sorting.
  • Sometimes it's desirable to have the comparison method separate from the value object class itself. For example, if there are different possible way of sorting, you could write different classes that implement Comparator interface and choose the one you need at a specific point in the program.
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.

Comments

Popular posts from this blog

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...