sorting - Why Guavas Ordering doesn't sort string values of integers correctly? -


i want know why guavas ordering doesn't works correctly @ follows code:

public static void main(string[] args) {     list<integer> integers = arrays.aslist(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);     system.out.println(ordering.natural().isordered(integers));      list<string> strings = arrays.aslist("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");     system.out.println(ordering.natural().isordered(strings));      list<string> strings2 = arrays.aslist("6417", "6418", "6419", "6420");     system.out.println(ordering.natural().isordered(strings2)); } 

output:

true false true 

i expected see true 3 times.

can explain why isn't sorted expected?

the ordering of strings based on lexicographical ordering defined in documentation, not on numerical ordering. pair of strings, first character of each of them taken , compared. if these equal, second character looked @ , on. string "10" "smaller" string "9", because character '1' smaller '9'.

note part of java api, , not specific guava. can @ output of "10".compareto("9") see this. ordering.natural() of guava calls compareto method of compared objects.

the reason strings arbitrary character sequences , not possible interpret of them numbers, numerical comparison fail. other programming languages handle in same way.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

Fatal error: Call to undefined function menu_execute_active_handler() in drupal 7.9 -

python - RuntimeWarning: PyOS_InputHook is not available for interactive use of PyGTK -