Rules for a.compareTo(b)
returns negative value
:a is before b
returns 0
:a equal to b
return 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/after
rules the order is4 34 23 15
Which is
Reverse Lexical Order
(Lexical because use ofString
, reverse because compare second to first)
Details for one case
- The
sort
method will compare4
and34
, sofirst=4
andsecond=34
- you compute
"344".compareTo("434")
, because 344 is before 434 is lexical order you got -1 - Because of
-1
thesort
method will remember that4
is before34
solved How does the Comparator works with Arrays.sort?