This week's book giveaway is in the Java in General forum.
We're giving away four copies of Helidon Revealed: A Practical Guide to Oracle’s Microservices Framework and have Michael Redlich on-line!
See this thread for details.
  • 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
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Comparator..

 
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,this from learnkey master exam.

import java.util.*;

class switch2
{

public static void main(String args[])
{
String[] sa={"Good","Gud","Bad","Ugly"};
Comparator<String> best=new Comparator<String>()
{
public int compare(String s1,String s2)
{
return s2.charAt(1)-s1.charAt(1);
}
};
Arrays.sort(sa,best);
for(String s:sa)
System.out.println(s);
}
}

output is gud,good,Ugly,bad.
can anyone explain me the logic of compare method using the above code?

Thanks
Preetha
 
Ranch Hand
Posts: 814
Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can refer to java API documentation
That doc says following things

I expalin with your code in short

public int compare(String s1,String s2)
{
return s2.charAt(1)-s1.charAt(1);
}

comparator sorts objects according to the values return by compare method that are 1, 0 and -1

when s1-s2 results 1 then s1 is greater than s2
when s1-s2 results 0 then s1 and s2 are equal
when s1-s2 results -1 then s1 is less than s2

And masre exam code is doing s2-s1 in compare method if this is the case then comparator is sorting objects in descending order

I hope this clears to you and inform me if I am wrong in somewhere in my explaination
 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One addition to what Ninad has said:

Here in this example, compare() method sorts the objects based on its character at index 1 and in descending order.

Hope this helps!
 
It's a tiny ad only because the water is so cold.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic