• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting Using Comparator

 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

This is my own program and i wrote this program depending up on example in K & B book [p/g 566].I could not understand that program and i tried that using String.

This is how i thought
o1<o2 returns -ve value
o1==o2 returns 0
o1>o2 returns +ve

import java.util.*;
import static java.lang.System.out;
class comp implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.charAt(1)-s1.charAt(1);//line 1
}
}
class Main3
{
public static void main(String... args)
{
String[] a={"anil","lalam","kumar"};
for(String s:a)
out.print(""+s);
out.println("\n\n");
Arrays.sort(a,new comp());
for(String s:a)
out.println("After :"+s);

}
}


How this working as reverse order?

Can any body explain me ?

Thanks
Anil Kumar
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


return s2.charAt(1)-s1.charAt(1);//line 1



It is reverse order on the character at index position 1 of the String.
Got it?


Thanks,
 
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Anil,

return s2.charAt(1)-s1.charAt(1);



Because of the above statement it is sorting reversly.If you change the statement as mentioned below sorting will not be in reverse order.
return s1.charAt(1)-s2.charAt(1)

Regards
Nik
[ June 13, 2007: Message edited by: nik arora ]
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks

nik and chandra....

I got it.

i did confuse a little bit.


Thanks

Anil Kumar
 
Beware the other head of science - it bites! Nibble on this message:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic