Comparison of version strings (Java implementation) when you want to branch the process between two versions

I wanted to change the system processing depending on the version of the task management service, so I implemented an implementation that compares the two version strings. It is a method to treat the version as a character string, divide it by a period, and then convert each part to Integer and compare.

Thing you want to do

--For example, you want to branch the process depending on whether the version of a service is 2.5 or higher and less than 2.5. --The version needs to consider three parts separated by periods of x.y.z, such as 2.5.0. --There are some ways to write versions such as 1.3-SNAPSHOT, 1.3a, but this time we will not consider them. --The version that becomes the branch point is fixed, and the character string of the service version is read from the configuration file.

Implementation

The implementation was written with reference to this site. For more detailed discussions, please refer to those who are interested.

I implemented the hashCode calculation myself. (I don't know if this is okay)

Version.java


package com.example;

import java.util.Arrays;
import java.util.ArrayList;

public class Version implements Comparable<Version> {
    
        private String version;
    
        private String[] parts;
    
        public final String getVersion() {
            return this.version;
        }
    
        public String[] getParts() {
            return this.parts;
        }
    
        public Version(String version) {
            if(version == null)
                throw new IllegalArgumentException("Version can not be null");
            if(!version.matches("[0-9]+(\\.[0-9]+)*"))
                throw new IllegalArgumentException("Invalid version format");
            this.version = version;
            this.parts = this.getVersion().split("\\.");
        }
    
        @Override public int compareTo(Version that) {
            if(that == null)
                return 1;
            String[] thisParts = this.getParts();
            String[] thatParts = that.getParts();
            int length = Math.max(thisParts.length, thatParts.length);
            for(int i = 0; i < length; i++) {
                int thisPart = i < thisParts.length ?
                        Integer.parseInt(thisParts[i]) : 0;
                int thatPart = i < thatParts.length ?
                        Integer.parseInt(thatParts[i]) : 0;
                if(thisPart < thatPart)
                    return -1;
                if(thisPart > thatPart)
                    return 1;
            }
            return 0;
        }
    
        @Override public boolean equals(Object that) {
            if(this == that)
                return true;
            if(that == null)
                return false;
            if(this.getClass() != that.getClass())
                return false;
            return this.compareTo((Version) that) == 0;
        }
    
        @Override public final int hashCode() {
            ArrayList<Integer> intParts = new ArrayList();
            String[] thisParts = this.getParts();
            for(int i = 0; i < thisParts.length; i++) {
                intParts.add(Integer.parseInt(thisParts[i]));
            }
            Integer[] list = intParts.toArray(new Integer[intParts.size()]);
            return Arrays.hashCode(list);
        }
    }

I tried to move the main function as follows.

Main.java


package com.example;

import com.example.Version;

public class Main {

    public static void main(String[] args) {
        Version a = new Version("1.1");
        Version b = new Version("1.1.1");
        System.out.println(a.compareTo(b)); // return -1 (a<b)
        System.out.println(a.equals(b));    // return false
        System.out.println(a.hashCode());
        System.out.println(b.hashCode());

        Version c = new Version("2.0");
        Version d = new Version("1.9.9");
        System.out.println(c.compareTo(d)); // return 1 (c>d)
        System.out.println(c.equals(d));   // return false
        System.out.println(c.hashCode());
        System.out.println(d.hashCode());

        Version e = new Version("2.06");
        Version f = new Version("2.060");
        System.out.println(e.compareTo(f));  // return -1 (e<f)
        System.out.println(e.equals(f));  // return false

        Version g = new Version("3.3.0");
        Version h = new Version("3.3.0");
        System.out.println(g.compareTo(h));  // return 0 (g==h)
        System.out.println(g.equals(h));  // return true
        System.out.println(g.hashCode());
        System.out.println(h.hashCode());
    }
}

Output


-1
false
993
30784
1
false
1023
31040
-1
false
0
true
32767
32767

For the time being, I thought it would be okay because it seems to be able to survive this way. Actually, I wanted to be able to use it even if a version such as 1.3-SNAPSHOT, 1.3a is written. .. ..

Reference / Citation

Recommended Posts

Comparison of version strings (Java implementation) when you want to branch the process between two versions
When you want to change the MySQL password of docker-compose
Code used when you want to process Json with only the standard library in Java (improved version) gson unnecessary
A memo when you want to clear the time part of the calendar
When you want to use the method outside
[rails] After option useful when you want to change the order of DB columns
[java tool] A useful tool when you want to send the ipmsg log of PC-A to the specified PC on a regular basis.
When you want to dynamically replace Annotation in Java8
Code to use when you want to process Json with only standard library in Java
I want to find out which version of java the jar file I have is available
Use JLine when you want to handle keystrokes on the console character by character in Java
When you want to reflect the Master Branch information in the Current Branch you are currently working on
I want to judge the necessity of testing by comparing the difference of class files when refactoring Java
How to write when you want to handle "array of C language strings" like argv [] in Ruby-FFI
When you want to check whether the contents of a property can be converted to a specific type
Switch the version of java installed by SDKMAN when moving directories
Output the difference between each field of two objects in Java
When you want to ZIP download the image data saved locally
If you want to change the Java development environment from Eclipse
Is the version of Elasticsearch you are using compatible with Java 11?
[Java version] The story of serialization
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
[Java] Input to stdin of Process
The first thing to do when you want to be happy with Heroku on GitHub with Eclipse in Java
Update JAVA to the latest version to 1.8.0_144 (when downloading from the web and updating)
I want to know the JSP of the open portlet when developing Liferay
Summary of means when you want to communicate with HTTP on Android
How to find out the Java version of a compiled class file
How to find the total number of pages when paging in Java
I want to get the IP address when connecting to Wi-Fi in Java
I want to get the field name of the [Java] field. (Old tale tone)
I want you to use Enum # name () for the Key of SharedPreference
How to install the legacy version [Java]
Output of the book "Introduction to Java"
[Java] Comparison of String type character strings
The process of introducing Vuetify to Rails
How to switch between multiple Java versions
If you want to satisfy the test coverage of private methods in JUnit
Defense Techniques When You Have to Fight the Performance of Unfamiliar Applications (Part 2)
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
I want you to use Scala as Better Java for the time being
A story confirming the implementation of the SendGrid Java library when mail delivery fails
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
Summary of copy and paste commands used when you want to delete the cache in iOS application development anyway
I want you to put the story that the error was solved when you stabbed the charger in the corner of your head