Rules for a.compareTo(b)
returns negative value:a is before breturns 0:a equal to breturn positive value:a is after b
Because the parameter are first, second and you compare like second.compareTo(first) you’ll get reverse order :
(second+first) 344 first+ second 434 comparing : -1 >> 4 is before 34
(second+first) 423 first+ second 234 comparing : 2 >> 23 is after 4
(second+first) 3423 first+ second 2334 comparing : 1 >> 23 is after 34
(second+first) 3415 first+ second 1534 comparing : 2 >> 15 is after 34
(second+first) 2315 first+ second 1523 comparing : 1 >> 15 is after 23
With these 5
before/afterrules the order is4 34 23 15Which is
Reverse Lexical Order(Lexical because use ofString, reverse because compare second to first)
Details for one case
- The
sortmethod will compare4and34, sofirst=4andsecond=34 - you compute
"344".compareTo("434"), because 344 is before 434 is lexical order you got -1 - Because of
-1thesortmethod will remember that4is before34
solved How does the Comparator works with Arrays.sort?