1. 程式人生 > 實用技巧 >比較APP版本號大小

比較APP版本號大小

	public static void main(String[] args) {
		String[] versions = { "1.9", "1.10", "1.0" };
		for (int i = versions.length - 1; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (compareAppVersion(versions[i], versions[j]) > 0) {
					String temp = versions[j];
					versions[j] = versions[j + 1];
					versions[j + 1] = temp;
				}
			}
		}
		System.out.println(JSON.toJSONString(versions));
	}

	/**
	 * 比較APP版本號的大小
	 * 1、前者大則返回一個正數
	 * 2、後者大返回一個負數
	 * 3、相等則返回0
	 */
	public static int compareAppVersion(String version1, String version2) {
        if (version1 == null || version2 == null) {
            throw new RuntimeException("版本號不能為空");
        }
        // 注意此處為正則匹配,不能用.
        String[] versionArray1 = version1.split("\\.");
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        // 取陣列最小長度值
        int minLength = Math.min(versionArray1.length, versionArray2.length);
        int diff = 0;
        // 先比較長度,再比較字元
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {
            ++idx;
        }
        // 如果已經分出大小,則直接返回,如果未分出大小,則再比較位數,有子版本的為大
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }