How do you compare two version Strings in Java?

2019-01-01 04:46发布

Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:

1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10

20条回答
几人难应
2楼-- · 2019-01-01 05:48
public static int compareVersions(String version1, String version2){

    String[] levels1 = version1.split("\\.");
    String[] levels2 = version2.split("\\.");

    int length = Math.max(levels1.length, levels2.length);
    for (int i = 0; i < length; i++){
        Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
        Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
        int compare = v1.compareTo(v2);
        if (compare != 0){
            return compare;
        }
    }

    return 0;
}
查看更多
皆成旧梦
3楼-- · 2019-01-01 05:49

for my projects I use my commons-version library https://github.com/raydac/commons-version it contains two auxiliary classes - to parse version (parsed version can be compared with another version object because it is comparable one) and VersionValidator which allows to check version for some expression like !=ide-1.1.1,>idea-1.3.4-SNAPSHOT;<1.2.3

查看更多
登录 后发表回答