0

I'm not sure as to how I'd go about comparing two version strings, and include support for "SNAPSHOT" in the version name.

An example: I have two version strings, "1.9.9" and "2.0.0". I want to return a boolean (true) if the second string is greater than the first string. I've used this: https://stackoverflow.com/a/6702029/1442718

It works perfectly.

However, an example like this won't work with that code: I have two version strings, "2.0.0-SNAPSHOT" and "2.0.0". Obviously the SNAPSHOT is one version behind 2.0.0, but this method won't pick it up and throw a NumberFormatException, instead of returning -1 which implies it is a version below.

Any suggestions? Thanks.

Community
  • 1
  • 1
Faris Rehman
  • 129
  • 1
  • 4
  • 11
  • Search for "-SNAPSHOT" in the string, and use the substring that precedes it if found for the numerical comparison – jalynn2 Jun 19 '15 at 16:44
  • 2
    You could use `boolean isSnapshot1 = str1.endsWith("SNAPSHOT")`. In case of equality regarding version-numbers, the "snapshot"-one wins. If both are snapshot and the versions are equal, you cannot distinguish their order. – Turing85 Jun 19 '15 at 16:46
  • Check your string to see if it contain "SNAPSHOT" `contains("SNAPSHOT")` and remove it from the string using `replace("SNAPSHOT", "")` – Armaiti Jun 19 '15 at 16:46
  • 1
    If you don't mind adding extra library, you can use maven's [ComparableVersion](https://maven.apache.org/ref/3.0.3/maven-artifact/apidocs/org/apache/maven/artifact/versioning/ComparableVersion.html) class. – Marko Gresak Jun 19 '15 at 16:46
  • @jalynn2 But that would return 0 as the strings are the same then.. – Faris Rehman Jun 19 '15 at 16:49
  • @Turing85 Oh right, makes sense! Thanks, I'll try that that. – Faris Rehman Jun 19 '15 at 16:50
  • @MarkoGrešak Sure, I'll check that out after I've tried the method suggested by Turing, thanks. – Faris Rehman Jun 19 '15 at 16:50
  • @Faris Rehman: If you found "-SNAPSHOT" change your comparison algorithm to account for it. – jalynn2 Jun 19 '15 at 16:51
  • @Turing85 Worked, thanks =) – Faris Rehman Jun 19 '15 at 17:07

1 Answers1

1

You could use something like this:

[...]
boolean isSnapshot1 = str1.endsWith("SNAPSHOT");
boolean isSnapshot2 = str2.endsWith("SNAPSHOT");
[...]
if (...) { // if version-number are equal
    if (isSnapshot1 && !isSnapshot2) { // same versions, but first is snapshot
        return (1);
    }
    if { // same versions, but secont is snapshot
        return (-1);
    }
    // else { Neither or both are snapshots, versions are equals -> cannot distinguish their order
        return (0);
    // }
}
[...]

This should to the job.

Turing85
  • 18,217
  • 7
  • 33
  • 58