Java Version Compare versionCompare(String ver1, String ver2)

Here you can find the source of versionCompare(String ver1, String ver2)

Description

Compare two given versions.

License

Open Source License

Parameter

Parameter Description
ver1 a parameter
ver2 a parameter

Declaration

public static long versionCompare(String ver1, String ver2) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) May 18, 2011 Zend Technologies Ltd. 
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Eclipse Public License v1.0 
 * which accompanies this distribution, and is available at 
 * http://www.eclipse.org/legal/epl-v10.html  
 *******************************************************************************/

public class Main {
    private final static String patternVersion = "\\d{1,3}.\\d{1,3}(.\\d{1,3})?(.\\d{1,3})?";

    /**/*from  w w w.ja v  a 2 s.  co  m*/
     * Compare two given versions.
     * 
     * <pre>
     * < 0
     * </pre>
     * 
     * ver1 is greater than ver2
     * 
     * <pre>
     * = 0
     * </pre>
     * 
     * ver1 is equal to ver2
     * 
     * <pre>
     * > 0
     * </pre>
     * 
     * ver1 is smaller than ver2
     * 
     * @param ver1
     * @param ver2
     * @return
     */
    public static long versionCompare(String ver1, String ver2) {
        if (invalidVersion(ver1) || invalidVersion(ver2)) {
            throw new IllegalArgumentException("illegal format of version: " + ver1 + " or " + ver2);
        }

        return normalizeVersion(ver1) - normalizeVersion(ver2);
    }

    public static boolean invalidVersion(String currentVersion) {
        return !currentVersion.matches(patternVersion);
    }

    public static long normalizeVersion(String version) {
        if (invalidVersion(version)) {
            throw new IllegalArgumentException("illegal format of version: " + version);
        }

        final String[] split = version.split("\\.");
        long sum = 0;
        for (int i = 0; i < split.length; i++) {
            sum += Integer.valueOf(split[i]) * Math.pow(10, (9 - i * 3));
        }

        return sum;
    }
}

Related

  1. versionCompare(String firstVersionString, String secondVersionString)
  2. versionCompare(String fromVersion, String toVersion)
  3. versionCompare(String str1, String str2)
  4. versionCompare(String str1, String str2)
  5. versionCompare(String userVersion, String supportVersion)
  6. VersionComparer(String a, String b, boolean includeEqual)