gpt4 book ai didi

Java版本号排序

转载 作者:搜寻专家 更新时间:2023-10-31 19:55:36 25 4
gpt4 key购买 nike

String[] k1 = {"0.10", "0.2", "0.1", "0", "1.10", "1.2", "1.1", "1", "2.10", "2", "2.2", "2.1"};
double[] k2 = {0.10, 0.2, 0.1, 0, 1.10, 1.2, 1.1, 1, 2.10, 2, 2.2, 2.1};
Arrays.sort(k1);
Arrays.sort(k2);
System.out.println(Arrays.toString(k1));
System.out.println(Arrays.toString(k2));

输出:

[0,   0.1, 0.10, 0.2,  1,   1.1, 1.10, 1.2,  2,   2.1, 2.10, 2.2]
[0.0, 0.1, 0.1, 0.2, 1.0, 1.1, 1.1, 1.2, 2.0, 2.1, 2.1, 2.2]

我想要的,

[0, 0.1, 0.2, 0.10, 1, 1.1, 1.2, 1.10, 2, 2.1, 2.2, 2.10]

首先在小数点之前和之后排序。像 1、1.1、1.2、1.10、2、2.1 等。

我如何为此编写一个比较器?

最佳答案

2.1, 2.2, 2.10]

由于 2.10 按此顺序大于 2.2,因此它看起来像版本号排序:

import java.util.Arrays;
import java.util.Comparator;

public class VersionNumberComparator implements Comparator<String> {
@Override
public int compare(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
int major1 = major(v1);
int major2 = major(v2);
if (major1 == major2) {
return minor(v1).compareTo(minor(v2));
}
return major1 > major2 ? 1 : -1;
}

private int major(String[] version) {
return Integer.parseInt(version[0]);
}

private Integer minor(String[] version) {
return version.length > 1 ? Integer.parseInt(version[1]) : 0;
}

public static void main(String[] args) {
String[] k1 = { "0.10", "0.2", "0.1", "0", "1.10", "1.2", "1.1", "1",
"2.10", "2", "2.2", "2.1" };
Arrays.sort(k1, new VersionNumberComparator());
System.out.println(Arrays.asList(k1));
}
}

关于Java版本号排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20375067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com