• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Please explain the code.

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

Can anybody explain me the the code.

Posts: 1776
  • 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.

Ranch Hand
Posts: 287
  • 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

It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!