• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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
 
The harder you work, the luckier you get. This tiny ad brings luck - just not good luck or bad luck.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic