'How Arrays.sort() works on numeric Strings [duplicate]
Greetings to the community!
I browsed a lot over the internet but couldn't find the answer in my case. My question is that when we provide an array of numeric strings to the Arrays.sort() how it sorts them. Like I have a string array that contains numbers
String[] numerics= {"1","2","3","12","-7"}
and when I apply
Arrays.sort(numerics)
Output comes as
Before Sorting
[1, 2, 3, 12, -7]
After Applying Arrays.sort()
[-7, 1, 12, 2, 3]
I want to know how Arrays.sort() sorts this string array.?
Solution 1:[1]
The answer from @Lee Boozer is correct. Strings are compared char by char until the first difference is found. The first different chars found are compared as ASCII and the result is the result of your String comparison. SO obviously with this "3" will be greater than "27". So, you can convert your Strings to Integers (or Long) and compare them or you can use an Open source library called MgntUtils that has a VersionComparator class that takes Strings such as "3.5.2" and "15.7" and compares them by comparing number by number delimited by "." so any numeric string like "5" or "27" will also be a valid version and as such could be compared with each other by VersionComparator. One drawback it doesn't work with negative numbers, and it is so by design. Here is Javadoc. The library could be found on Maven central here and on Github including Javadoc and source code here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael Gantman |
