Java:对String数组进行排序,其字符串表示int [英] Java: sort a String array, whose strings represent int
本文介绍了Java:对String数组进行排序,其字符串表示int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 String []
数组如
{"3","2","4","10","11","6","5","8","9","7"}
我想按数字顺序对其进行排序,而不是按字母顺序排序。
I want to sort it in numerical order, not in alphabetical order.
如果我使用
Arrays.sort(myarray);
我获得
{"10","11","2","3","4","5","6","7","8","9"}
而不是
{"2","3","4","5","6","7","8","9","10","11"}
推荐答案
我认为到目前为止转换字符串
s到 int
s:
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];
}
另一种方法是使用比较器界面,用于确切地说明元素的比较方式,但这可能相当于无论如何将每个 String
值转换为 int
- 使上述方法更有效。
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.
这篇关于Java:对String数组进行排序,其字符串表示int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文