• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays.sort with comparator

 
charla Vella
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 679
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
Firefox Browser Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic