是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
当前回答
科特林:
@kotlin.jvm.Throws(InvalidParameterException::class)
fun String.versionCompare(remoteVersion: String?): Int {
val remote = remoteVersion?.splitToSequence(".")?.toList() ?: return 1
val local = this.splitToSequence(".").toList()
if(local.filter { it.toIntOrNull() != null }.size != local.size) throw InvalidParameterException("version invalid: $this")
if(remote.filter { it.toIntOrNull() != null }.size != remote.size) throw InvalidParameterException("version invalid: $remoteVersion")
val totalRange = 0 until kotlin.math.max(local.size, remote.size)
for (i in totalRange) {
if (i < remote.size && i < local.size) {
val result = local[i].compareTo(remote[i])
if (result != 0) return result
} else (
return local.size.compareTo(remote.size)
)
}
return 0
}
其他回答
使用Java 9自带的Version类
import java.util.*;
import java.lang.module.ModuleDescriptor.Version;
class Main {
public static void main(String[] args) {
var versions = Arrays.asList(
"1.0.2",
"1.0.0-beta.2",
"1.0.0",
"1.0.0-beta",
"1.0.0-alpha.12",
"1.0.0-beta.11",
"1.0.1",
"1.0.11",
"1.0.0-rc.1",
"1.0.0-alpha.1",
"1.1.0",
"1.0.0-alpha.beta",
"1.11.0",
"1.0.0-alpha.12.ab-c",
"0.0.1",
"1.2.1",
"1.0.0-alpha",
"1.0.0.1", // Also works with a number of sections different than 3
"1.0.0.2",
"2",
"10",
"1.0.0.10"
);
versions.stream()
.map(Version::parse)
.sorted()
.forEach(System.out::println);
}
}
在网上试试!
输出:
0.0.1
1.0.0-alpha
1.0.0-alpha.1
1.0.0-alpha.12
1.0.0-alpha.12.ab-c
1.0.0-alpha.beta
1.0.0-beta
1.0.0-beta.2
1.0.0-beta.11
1.0.0-rc.1
1.0.0
1.0.0.1
1.0.0.2
1.0.0.10
1.0.1
1.0.2
1.0.11
1.1.0
1.2.1
1.11.0
2
10
// VersionComparator.java
import java.util.Comparator;
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1 = 0, number2 = 0;
String suffix1 = "", suffix2 = "";
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
}
// VersionTokenizer.java
public class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
public int getNumber() {
return _number;
}
public String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
public VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
例子:
public class Main
{
private static VersionComparator cmp;
public static void main (String[] args)
{
cmp = new VersionComparator();
Test(new String[]{"1.1.2", "1.2", "1.2.0", "1.2.1", "1.12"});
Test(new String[]{"1.3", "1.3a", "1.3b", "1.3-SNAPSHOT"});
}
private static void Test(String[] versions) {
for (int i = 0; i < versions.length; i++) {
for (int j = i; j < versions.length; j++) {
Test(versions[i], versions[j]);
}
}
}
private static void Test(String v1, String v2) {
int result = cmp.compare(v1, v2);
String op = "==";
if (result < 0) op = "<";
if (result > 0) op = ">";
System.out.printf("%s %s %s\n", v1, op, v2);
}
}
输出:
1.1.2 == 1.1.2 ---> same length and value
1.1.2 < 1.2 ---> first number (1) less than second number (2) => -1
1.1.2 < 1.2.0 ---> first number (1) less than second number (2) => -1
1.1.2 < 1.2.1 ---> first number (1) less than second number (2) => -1
1.1.2 < 1.12 ---> first number (1) less than second number (12) => -1
1.2 == 1.2 ---> same length and value
1.2 == 1.2.0 ---> first shorter than second, but zero
1.2 < 1.2.1 ---> first shorter than second, and non-zero
1.2 < 1.12 ---> first number (2) less than second number (12) => -1
1.2.0 == 1.2.0 ---> same length and value
1.2.0 < 1.2.1 ---> first number (0) less than second number (1) => -1
1.2.0 < 1.12 ---> first number (2) less than second number (12) => -1
1.2.1 == 1.2.1 ---> same length and value
1.2.1 < 1.12 ---> first number (2) less than second number (12) => -1
1.12 == 1.12 ---> same length and value
1.3 == 1.3 ---> same length and value
1.3 > 1.3a ---> first suffix ('') is empty, but not second ('a') => 1
1.3 > 1.3b ---> first suffix ('') is empty, but not second ('b') => 1
1.3 > 1.3-SNAPSHOT ---> first suffix ('') is empty, but not second ('-SNAPSHOT') => 1
1.3a == 1.3a ---> same length and value
1.3a < 1.3b ---> first suffix ('a') compared to second suffix ('b') => -1
1.3a < 1.3-SNAPSHOT ---> first suffix ('a') compared to second suffix ('-SNAPSHOT') => -1
1.3b == 1.3b ---> same length and value
1.3b < 1.3-SNAPSHOT ---> first suffix ('b') compared to second suffix ('-SNAPSHOT') => -1
1.3-SNAPSHOT == 1.3-SNAPSHOT ---> same length and value
使用Maven真的很简单:
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1");
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10");
DefaultArtifactVersion version = new DefaultArtifactVersion("1.11");
if (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {
System.out.println("Sorry, your version is unsupported");
}
您可以从这个页面获得Maven Artifact的正确依赖项字符串:
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>3.0.3</version>
</dependency>
public class VersionComparator {
/* loop through both version strings
* then loop through the inner string to computer the val of the int
* for each integer read, do num*10+<integer read>
* and stop when stumbling upon '.'
* When '.' is encountered...
* see if '.' is encountered for both strings
* if it is then compare num1 and num2
* if num1 == num2... iterate over p1++, p2++
* else return (num1 > num2) ? 1 : -1
* If both the string end then compare(num1, num2) return 0, 1, -1
* else loop through the longer string and
* verify if it only has trailing zeros
* If it only has trailing zeros then return 0
* else it is greater than the other string
*/
public static int compareVersions(String v1, String v2) {
int num1 = 0;
int num2 = 0;
int p1 = 0;
int p2 = 0;
while (p1 < v1.length() && p2 < v2.length()) {
num1 = Integer.parseInt(v1.charAt(p1) + "");
num2 = Integer.parseInt(v2.charAt(p2) + "");
p1++;
p2++;
while (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) != '.' && v2.charAt(p2) != '.') {
if (p1 < v1.length()) num1 = num1 * 10 + Integer.parseInt(v1.charAt(p1) + "");
if (p2 < v2.length()) num2 = num2 * 10 + Integer.parseInt(v2.charAt(p2) + "");
p1++;
p2++;
}
if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.' && v2.charAt(p2) == '.') {
if ((num1 ^ num2) == 0) {
p1++;
p2++;
}
else return (num1 > num2) ? 1 : -1;
}
else if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.') return -1;
else if (p1 < v1.length() && p2 < v2.length() && v2.charAt(p2) == '.') return 1;
}
if (p1 == v1.length() && p2 == v2.length()) {
if ((num1 ^ num2) == 0) return 0;
else return (num1 > num2) ? 1 : -1;
}
else if (p1 == v1.length()) {
if ((num1 ^ num2) == 0) {
while (p2 < v2.length()) {
if (v2.charAt(p2) != '.' && v2.charAt(p2) != '0') return -1;
p2++;
}
return 0;
}
else return (num1 > num2) ? 1 : -1;
}
else {
if ((num1 ^ num2) == 0) {
while (p1 < v1.length()) {
if (v1.charAt(p1) != '.' && v1.charAt(p1) != '0') return 1;
p1++;
}
return 0;
}
else return (num1 > num2) ? 1 : -1;
}
}
public static void main(String[] args) {
System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1);
System.out.println(compareVersions("11.21.1.0.0.1.0", "11.23") ^ -1);
System.out.println(compareVersions("11.23", "11.23.0.0.0.1.0") ^ -1);
System.out.println(compareVersions("11.2", "11.23") ^ -1);
System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1);
System.out.println(compareVersions("1.21.1.0.0.1.0", "2.23") ^ -1);
System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1);
System.out.println(compareVersions("11.23.0.0.0.0.0", "11.23") ^ 0);
System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1);
System.out.println(compareVersions("1.5.1.3", "1.5.1.3.0") ^ 0);
System.out.println(compareVersions("1.5.1.4", "1.5.1.3.0") ^ 1);
System.out.println(compareVersions("1.2.1.3", "1.5.1.3.0") ^ -1);
System.out.println(compareVersions("1.2.1.3", "1.22.1.3.0") ^ -1);
System.out.println(compareVersions("1.222.1.3", "1.22.1.3.0") ^ 1);
}
}
我写了一个名为MgntUtils的开源库,它有一个用于字符串版本的实用程序。它正确地比较它们,适用于版本范围等等。下面是这个库javadoc参见方法TextUtils.comapreVersions(…)它已经被大量使用并经过了良好的测试。下面这篇文章描述了这个库以及如何获取它。它可以作为Maven工件和在github上获得(包括源代码和JavaDoc)