Comparing version number strings (major, minor, revision, beta)

前端 未结 3 1178
花落未央
花落未央 2021-01-04 05:58

I have an application that communicates with the firmware of a device. As there are changes to the firmware, it is versioned with the format {major}.{minor}.{revision}

3条回答
  •  梦毁少年i
    2021-01-04 06:38

    I would implement a comparable class:

    class Version implements Comparable {
        int major;
        int minor;
        int rev;
        int beta = Integer.MAX_VALUE;
    
    
        public int compareTo(Version o) {
            if (this.major != o.major) {
                return Integer.compare(this.major, o.major);
            }
            if (this.minor != o.minor) {
                return Integer.compare(this.minor, o.minor);
            }
            if (this.rev != o.rev) {
                return Integer.compare(this.rev, o.rev);
            }
            if (this.beta != o.beta) {
                return Integer.compare(this.beta, o.beta);
            }
            return 0;
        }
    
    
        public static Version parse(String version) {
            // TODO: implement parsing here
            // 1.1.1      - beta = MAX_VALUE
            // 1.1.1beta  - beta = 1
            // 1.1.1beta2 - beta = 2
            return new Version();
        }
    
    
        @Override
        public String toString() {
            return "" + major + "." + minor + "." + rev
                    + (beta == Integer.MAX_VALUE ? "" 
                            : (beta == 1 ? "beta" : 
                                ("beta" + beta)));
        }
    
    
    }
    

    Then compare in a standard java way:

    if (Version.parse(testFW).compareTo(Version.parse(baseFW)) < 0) {
       // Version is newer!
    }
    

提交回复
热议问题