参考文章:http://www.jb51.net/article/70317.htm
关键点
为什么不能使用String.compareTo方法来比较客户端版本号?
举个例子,之前客户端版本号为:9.9.9,而服务器端最新的客户端版本号为:10.0.1,虽然10.0.1明显高于9.9.9,但是按照compareTo方法,这个9.9.9是大于10.0.1的,导致客户端版本号比较错误。
Java代码实现
public class CompareVersion { public static void main(String[] args) { System.out.println(compareVersion("2.0.0", "2.0.1")); } public static int compareVersion(String version1, String version2) { if (version1.equals(version2)) { return 0; } String[] version1Array = version1.split("\\."); String[] version2Array = version2.split("\\."); int index = 0; int minLen = Math.min(version1Array.length, version2Array.length); int diff = 0; while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) { index ++; } if (diff == 0) { for (int i = index; i < version1Array.length; i ++) { if (Integer.parseInt(version1Array[i]) > 0) { return 1; } } for (int i = index; i < version2Array.length; i ++) { if (Integer.parseInt(version2Array[i]) > 0) { return -1; } } return 0; } else { return diff > 0 ? 1 : -1; } } }