Class VersionStringComparator

java.lang.Object
ca.corbett.updates.VersionStringComparator
All Implemented Interfaces:
Comparator<String>

public class VersionStringComparator extends Object implements Comparator<String>
Compares String versions in a sane and predictable way. String sorting of numeric values is inherently unreliable, and winds up with wonkiness like "11.0" being sorted ahead of "2.0". This Comparator makes use of convertVersionToSafeCompareString() in this class to compare version strings in a more predictable way.
Since:
swing-extras 2.5
Author:
scorbo2
  • Constructor Details

    • VersionStringComparator

      public VersionStringComparator()
  • Method Details

    • convertVersionToSafeCompareString

      public static String convertVersionToSafeCompareString(String version)
      Given a version string in the format "x.y.z", return a String that is safe for use in string comparison operations. This involves removing the dots and then zero-padding each component number to three digits. So, "1.2" returns "001002000", and "1.21.5" returns "001021005".

      The intention is to avoid weird sorting errors like "11.0" being sorted before "2.1", which is what would happen without this method.

      Versions are normalized to 3 segments. Missing segments are treated as 0. Non-numeric characters are stripped from each segment (e.g., the "v" in "v1.0" is removed). So, "v1-SNAPSHOT" would return "001000000", because we implicitly read that as "1.0.0". Extra version numbers beyond Major.Minor.Patch are simply ignored. So, "1.0.0.1.0" would evaluate to "001000000".

    • isAtLeast

      public static boolean isAtLeast(String candidateVersion, String targetVersion)
      Convenience method to quickly compare a candidate version and report if it is at least (equal to or newer than) the given target version.
    • isAtMost

      public static boolean isAtMost(String candidateVersion, String targetVersion)
      Convenience method to quickly compare a candidate version and report if it is at most (equal to or older than) the given target version.
    • isExactly

      public static boolean isExactly(String candidateVersion, String targetVersion)
      Convenience method to quickly compare a candidate version and report if it is exactly equal to the given target version.
    • isNewerThan

      public static boolean isNewerThan(String candidateVersion, String targetVersion)
      Convenience method to quickly compare a candidate version and report if it is newer (higher version number) than the given target version.
    • isOlderThan

      public static boolean isOlderThan(String candidateVersion, String targetVersion)
      Convenience method to quickly compare a candidate version and report if it is older (lower version number) than the given target version.
    • compare

      public int compare(String o1, String o2)
      Specified by:
      compare in interface Comparator<String>