• 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

Really Confused about using the Comparator Interface in Collections

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The result given in the LearnKey exam is Good Please help explaining this?
 
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
In lines 5 to 8, there is an anonymous inner class that implements Comparator<String>.

Line 6 is the start of the compare method of the Comparator.

In line 7, the two strings are compared by looking at the first character of each string and subtracting the two char values. This gives a value, which is returned as an int (positive, zero or negative), which determines the sort order. Lookup the API documentation of String.charAt(...).

In line 9, the comparator 'best' is used to sort the string array 'words'.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public int compare(Object o1,
Object o2)Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
The line "return s2.charAt(1) - s1.charAt(1); " is comparing the two string by subtracting the Integer values of the second character of your string.
 
Dhruv Arya
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Got it thanks guys maybe going too much into it got me confused thanks for the help
reply
    Bookmark Topic Watch Topic
  • New Topic