This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain the code.

 
Vijay Tidake
Ranch Hand
Posts: 146
Hibernate Java Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can anybody explain me the the code.



Thanks
 
John Jai
Rancher
Posts: 1776
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class implements the Comparator interface. So when a Array.sort() method is called, it uses the specified comparator (here the class VLA2) to compare objects during sorting.

The VLA2 class overrides the compare() method of the Comparator interface. This is the method that will be called to compare objects.

Please read the specifications - Comparator:compare(), http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(T[], java.util.Comparator) and the Comparators section in Object Ordering Tutorials.

I think the compare method written in the code is wrong. According to the specification it should return a negative int / zero or a positive int. But it just assigns the given a's dish value to b and returns it.

And http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(T[], T, java.util.Comparator) is used
to search the given object, using the given comparator in the given array.

I have modified the compare() method and added some System.out.println() and two more objects in the array in the code shown below.
Note that binarySearch() method uses the comparator to find the object.


 
Harsha Smith
Ranch Hand
Posts: 287
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, the compare method is very badly implemented. The following code includes binarySearch(as it is done in Arrays class) gives you more clarity. Includes overriden toString() method




 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic