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

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

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

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v