Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help with practice question implememting Comparator Interface

 
Panindra Chekoori
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The Arrays.sort(T[] , Comparator) method sorts the elements of an array using an Comparator object. I just wanted to know if the object v[0] mentioned on lines #1, #2, #3 is used for a particular reason in the program. I replaced v[0] with v[1], v[2] which are also Comparator objects of the same class and obtained the same output. Does it means that the argument can be any Comparator object that is an instance of the class? Secondly, I am unable to understand the compare method's behavior of sorting objects based on custom sort (#4) provided by the user. The study guide gives information about negative, positive, zero return values that the method returns but how can these values help in sorting the objects accordingly.
OCP Practice Exams guide
Assessmant Test2- Question #1
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fitstly, the argument can be any Comparator<VLA2>. So yes, you can use any of va[0], va[1] and va[2] in that slot. In fact, you'd never do this in real code - it's an artificial setup for a question. There's no point in making an object into a comparator for the same class. Instead you'd do one of two things:

- If it's a natural ordering, you'd have the class implement the Comparable interface. Then you just omit the final argument.

- Otherwise, have a separate class that implements the Comparator interface, and use an instance of that. In that case, I'd often use a static inner class of the class being sorted.

For the second part - the sort routines work by successively comparing pairs of items to see what order they should be in. So a single method that tells you that is all you need to provide - and that's what the compare() method effectively does.
 
dennis deems
Ranch Hand
Posts: 808
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Panindra Chekoori wrote:Secondly, I am unable to understand the compare method's behavior of sorting objects based on custom sort (#4) provided by the user. The study guide gives information about negative, positive, zero return values that the method returns but how can these values help in sorting the objects accordingly.

A data structure that takes a comparator to sort its elements will use the value returned by the compare method to decide whether the positions of the two objects need to be swapped. Note that the custom implementation here will sort the objects in reverse order.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic