任何人都可以告诉对以下字符串' index'进行排序的最佳(简单)方法是什么? java中的数组
String [] menuIndex= { "0",
"1",
"2",
"3",
"0.0",
"0.0.1",
"0.0.0",
"0.0.4",
"14" ,
"14.0",
"0.1" };
I need the sorted array in the following format
0,
0.0,
0.0.0,
0.0.1,
0.0.4,
0.1,
1,
2,
3,
14,
14.0
Plz帮助......
答案 0 :(得分:3)
由于您已经更改了要求,因此您自己的比较器是正确的解决方案。
import java.util.Arrays;
import java.util.Comparator;
public class MyCmp implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String[] parts1 = o1.split("\\.");
String[] parts2 = o2.split("\\.");
int max = Math.max(parts1.length, parts2.length);
for (int i = 0; i < max; i++) {
if (i < parts1.length && i < parts2.length) {
Integer i1 = Integer.parseInt(parts1[i]);
Integer i2 = Integer.parseInt(parts2[i]);
if (i1 == i2)
continue;
return i1.compareTo(i2);
}
if (i < parts1.length) {
return 1;
}
if (i < parts2.length) {
return -1;
}
}
return 0;
}
public static void main(String[] args) {
String[] menuIndex = { "0",
"1",
"2",
"3",
"0.0",
"0.0.1",
"0.0.0",
"0.0.4",
"14",
"14.0",
"0.1" };
Arrays.sort(menuIndex, new MyCmp());
System.out.println(Arrays.toString(menuIndex));
}
}
答案 1 :(得分:1)
创建自己的比较器并使用它对数组进行排序。
答案 2 :(得分:0)
使用Arrays.sort方法进行排序。下面是代码。
String [] menuIndex= { "0","1","2","3","0.0","0.0.1","0.0.0","0.0.4","4","4.0","0.1"};
Arrays.sort(menuIndex);
for(String str:menuIndex){
System.out.println(str);
}