aspose file tools*
The moose likes Java in General and the fly likes Arrays.sort with comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Arrays.sort with comparator" Watch "Arrays.sort with comparator" New topic
Author

Arrays.sort with comparator

charla Vella
Greenhorn

Joined: Jul 02, 2007
Posts: 2
thanks Nir, have another query please



it says that this program should output, "40 200 60 -2", followed by an exception
the reason being is that Arrays.sort() assumes that the elements of the array to be sorted implement comparable unless you provide a Comparator.
I am a bit confused can anyone please explain this to me thanks
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
charla Vella wrote:followed by an exception
the reason being is that Arrays.sort() assumes that the elements of the array to be sorted implement comparable unless you provide a Comparator.
I am a bit confused can anyone please explain this to me thanks

What bit is confusing you ? The VLA class doesn't implement Comparable and you haven't passed a Comparator instance to the sort method and so an exception is thrown.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

1. general rule is that array should be sorted before passing to binarySearch
2. Arrays.sort(oneargument[]) assumes all the objects in arrays are comparable and do process.
since Comparator is not a Comparable you get error
3. if you want to use comparator there is also Arrays.sort(two parameters)-use this.
sarvesh dikonda
Ranch Hand

Joined: Apr 08, 2012
Posts: 58

charla Vella wrote:thanks Nir, have another query please



it says that this program should output, "40 200 60 -2", followed by an exception
the reason being is that Arrays.sort() assumes that the elements of the array to be sorted implement comparable unless you provide a Comparator.
I am a bit confused can anyone please explain this to me thanks


The exception you were getting was because of the statement-Arrays.sort(vla); Here, you were trying to sort the Array using the compareTo() in Comparable interface which is by default and is only used unless you don't define an external method compare() from Comparator interface for SORTING by some other logic or by other parameters.

Try this code and the output you would get is,
40 200 60 -2
40 60 200 1
This will help you understand better!


Always believe in yourself
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arrays.sort with comparator
 
Similar Threads
SCJP Objective 6.5 Question
Sorting wih Comparator dont work ?
Please explain the code.
Need help with practice question implememting Comparator Interface
java.lang.Comparable and classcastexception probs yo - from OCP Exam 2 by K and B