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

本文介绍了一种基于Java实现的版本号比较方法,通过自定义`DeviceVersion`类并实现`Comparable`接口来完成版本号的比较逻辑。该方法适用于格式为`xx.xx.xx.xx`的版本号,通过将每个部分转换为整数并进行比较,从而实现版本号的正确排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求是这样,版本号规则  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值