java實現版本號碼的比較

來源:互聯網
上載者:User

標籤:

  之前比較用戶端版本號碼,一直用的是String.compareTo,知道出現bug之後才明白了它的不完善地方。它的比較方式是按照字串的比較來執行的,所以它有不正確的地方。舉個例子,之前用戶端版本號碼為:9.9.9,而伺服器端最新的用戶端版本號碼為:10.0.1,雖然10.0.1明顯高於9.9.9,但是按照compareTo方法,這個9.9.9是大於10.0.1的,導致用戶端版本號碼比較錯誤。下面是分隔後的版本號碼轉化為Integer值來比較,不過,還是首先比較的個數

 1 public static int compareVersion(String version1, String version2) { 2     if (version1.equals(version2)) { 3         return 0; 4     } 5     String[] version1Array = version1.split("//."); 6     String[] version2Array = version2.split("//."); 7     int index = 0; 8     //擷取最小長度值 9     int minLen = Math.min(version1Array.length, version2Array.length);10     int diff = 0;11     //迴圈判斷每位的大小12     while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {13         index++;14     }15     if (diff == 0) {16         //如果位元不一致,比較多餘位元17         for (int i = index; i < version1Array.length; i++) {18             if (Integer.parseInt(version1Array[i]) > 0) {19                 return 1;20             }21         }22 23         for (int i = index; i < version2Array.length; i++) {24             if (Integer.parseInt(version2Array[i]) > 0) {25                 return -1;26             }27         }28         return 0;29     } else {30         return diff > 0 ? 1 : -1;31     }32 }

 

java實現版本號碼的比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.