这个想法是将每个字符串转换为整数元组(NumberInfo
例如,我们将其命名),即“100.2.0”=> { 100, 2, 0 },因为整数表示对于执行比较很有用(比较用于排序项目)。
因此,在转换为 之后List<String>
,List<NumberInfo>
可以List<NumberInfo>
对 进行排序。
“元组”:
class NumberInfo {
private int a;
private int b;
private int c;
private NumberInfo(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
int getA() {
return a;
}
int getB() {
return b;
}
int getC() {
return c;
}
public static NumberInfo fromString(String s) {
String[] itemComponents = s.split("[.]");
if (itemComponents.length != 3) {
throw new IllegalArgumentException("Three comma delimited components expected");
}
int a = Integer.parseInt(itemComponents[0]);
int b = Integer.parseInt(itemComponents[1]);
int c = Integer.parseInt(itemComponents[2]);
NumberInfo numberInfo = new NumberInfo(a, b, c);
return numberInfo;
}
@Override
public String toString() {
return a + "." + b + "." + c;
}
}
元组比较器:
class NumberInfoComparator implements Comparator<NumberInfo> {
@Override
public int compare(NumberInfo o1, NumberInfo o2) {
int result = Integer.compare(o1.getA(), o2.getA());
if (result != 0)
return result;
result = Integer.compare(o1.getB(), o2.getB());
if (result != 0) {
return result;
}
result = Integer.compare(o1.getC(), o2.getC());
return result;
}
}
主要方法:
public static void main(String[] args) {
String[] tab = { "100.2.0" , "5.7.4" , "7.6.1" , "5.6.4" };
ArrayList<NumberInfo> numberInfoList = new ArrayList<NumberInfo>();
for (String item : tab) {
NumberInfo numberInfo = NumberInfo.fromString(item);
numberInfoList.add(numberInfo);
}
NumberInfoComparator numberInfoComparator = new NumberInfoComparator();
Collections.sort(numberInfoList, numberInfoComparator);
for (NumberInfo numberInfo : numberInfoList) {
System.out.println(numberInfo);
}
}