This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Comaparable is an interface which indicates that an object may be compared with another Comparable object. Comparator is an interface which indicates that an object may be used to compare other objects. They are quite different concepts. The API javadoc for Comparable is here and the API javadoc for Comparator is here. What is it that you are unclear about ?
The examples given in the API documentation for Comparable and Comparator interfaces, give an impression that both do the same job; except that 1. the compareTo method of Comparable interface is invoked by an object of a class, that implements the interface and another object which needs to be compared with is passed as an argument to this method. 2. the compare method of the Comparator interface receives two arguments which are objects to be compared. Is it that, the objects compared by the compareTo method belong to the same class, and the objects compared using compare method are objects to different subclasses of the same parent class?
Joined: Jan 07, 1999
Not really. It's more general than that. 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. When deciding which of the two appraches to use, you need to decide where you wish to put the comparison code. In some cases it makes sense to build an external Comparator - particularly where the container may contain a wide variety of object types and/or the comparison rules are complex. If the comparison rules are simple and all the objects in the collection are of a single type, it's often easier to make them Comparable and let the container do the comparing. Is this making any more sense?
Joined: May 19, 2001
The difference between Comparable and Comparator interfaces, does make sense to me now. Thankyou Frank.