• 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

Comparator

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Following is a question from K&B mock exam.

import java.util.*;

class Comp2{
public static void main(String args[]){
String[] words = {"Good", "Bad", "Ugly"};

Comparator<String> best = new Comparator<String>(){
public int compare(String s1, String s2){
return s2.charAt(1) - s1.charAt(1);
}
};

Arrays.sort(words, best);
System.out.println(words[0]);
}
}

ANS: Good

I'm always confused with Comparator. I could not get what exactly the s2.charAt(1) - s1.charAt(1); will do. How exactly it'll reverse the list? If it reverses the list then the list should be {"Ugly", "Bad", "Good"}. In this case, the words[0] should be-- Ugly.

Anyone, pls. clarify this to me - How the output is 'GOOD'?
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

How exactly it'll reverse the list?


The Comparator interface doesnt explicitly reverse the collection or the array, instead it gives the ability to sort based on the implementation of the compare().

In your example, array 'words' is sorted in descending order based on the second character of the String elements.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy,

for a normal (non-reversed) ordering you'll have to substract
s1 - s2

but here it it reverse because of
s2 - s1


and because the ordering is on the second letter (charAt(1)) the sequence would be
Good
Ugly
Bad


Yours,
Bu.
[ November 11, 2007: Message edited by: Burkhard Hassel ]
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sujatha M, please check your private messages. You can see them by clicking My Private Messages.
 
Aaaaaand ... we're on the march. Stylin. Get with it tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic