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.

asked Jun 19, 2015 at 16:40
8
  • Search for "-SNAPSHOT" in the string, and use the substring that precedes it if found for the numerical comparison Commented Jun 19, 2015 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. Commented Jun 19, 2015 at 16:46
  • Check your string to see if it contain "SNAPSHOT" contains("SNAPSHOT") and remove it from the string using replace("SNAPSHOT", "") Commented Jun 19, 2015 at 16:46
  • 1
    If you don't mind adding extra library, you can use maven's ComparableVersion class. Commented Jun 19, 2015 at 16:46
  • @jalynn2 But that would return 0 as the strings are the same then.. Commented Jun 19, 2015 at 16:49

1 Answer 1

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.

answered Jun 20, 2015 at 18:54
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the late reply, yeah thanks, that's what I did and it works great.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.