Need help with practice question implememting Comparator Interface
Joined: Oct 27, 2011
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 mentioned on lines #1, #2, #3 is used for a particular reason in the program. I replaced v with v, v 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
Fitstly, the argument can be any Comparator<VLA2>. So yes, you can use any of va, va and va 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.
Joined: Mar 12, 2011
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.