Sort a String array, whose strings represent int
java, sorting
Solution
I think by far the easiest and most efficient way it to convert the `String`s to `int`s:
int[] myIntArray = new int[myarray.length];
for (int i = 0; i < myarray.length; i++) {
myIntArray[i] = Integer.parseInt(myarray[i]);
}
And then sort the integer array. If you really need to, you can always convert back afterwards:
for (int i = 0; i < myIntArray.length; i++) {
myarray[i] = "" + myIntArray[i];
}
An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each `String` value to an `int` anyway - making the above approach much more efficient.
Problem
I have `String[]` array like ``` {"3","2","4","10","11","6","5","8","9","7"} ``` I want to sort it in numerical order, not in alphabetical order. If I use ``` Arrays.sort(myarray); ``` I obtain ``` {"10","11","2","3","4","5","6","7","8","9"} ``` instead of ``` {"2","3","4","5","6","7","8","9","10","11"} ```