版本号比较,获取最新版本号

需求是这样,版本号规则  xx.xx.xx.xx 其中x为0-9的数字,例1.0.10.11  1.0.10.9 其中1.0.10.11为最新版本号

先比较高位数字大小,依次类推

按规则比较对象大小,可以实现Comparable接口,重写比较规则,然后在比较对象进行排序

 1 public class DeviceVersion implements Comparable<Object>{
 2     private String module_version; // 模块版本号  格式 x.x.x.xx
 3 
 4     public String getModule_version() {
 5         return module_version;
 6     }
 7 
 8     public void setModule_version(String module_version) {
 9         this.module_version = module_version;
10     }
11 
12 
13     @Override
14     public int compareTo(Object object) {
15         if(this == object){
16             return 0;
17         }else if (object!=null && object instanceof DeviceVersion) {
18             //支持格式 xx.xx.xx.xx 的比较
19             DeviceVersion deviceVersion = (DeviceVersion) object;
20             String[] version1 = module_version.split("\."); // 此处注意转义,split使用。和| 时,需要转义
21             String[] version2 = deviceVersion.getModule_version().split("\.");
22             // 转成int进行比较
23             int value1 = Integer.parseInt(version1[0])*1000000+Integer.parseInt(version1[1])*10000+Integer.parseInt(version1[2])*100+Integer.parseInt(version1[3]);
24             int value2 = Integer.parseInt(version2[0])*1000000+Integer.parseInt(version2[1])*10000+Integer.parseInt(version2[2])*100+Integer.parseInt(version2[3]);
25             return value2 - value1;
26         }else{
27             return -1;
28         }
29 
30     }
31 }
View Code


测试一下

public class LatestVersion {
    private static final Comparator<DeviceVersion> COMPARATOR = new Comparator<DeviceVersion>() {
        public int compare(DeviceVersion o1, DeviceVersion o2) {
            return o1.compareTo(o2);
        }
    };
    // 获取最新版本
    public static void main( String[] args ) {
        DeviceVersion deviceVersion1 = new DeviceVersion();
        deviceVersion1.setModule_version("2.0.0.1");
        DeviceVersion deviceVersion2 = new DeviceVersion();
        deviceVersion2.setModule_version("1.99.99.99");
        DeviceVersion deviceVersion3 = new DeviceVersion();
        deviceVersion3.setModule_version("2.0.0.11");
        List<DeviceVersion> deviceVersionList = new ArrayList<DeviceVersion>();
        deviceVersionList.add(deviceVersion1);
        deviceVersionList.add(deviceVersion2);
        deviceVersionList.add(deviceVersion3);
        Collections.sort(deviceVersionList,COMPARATOR);
        System.out.println(deviceVersionList.get(0).getModule_version());
    }

}
View Code

打印结果  2.0.0.11

原文地址:https://www.cnblogs.com/iiot/p/4384041.html