当前位置:   article > 正文

Java 比较两个版本号的大小 (通用)_java实现版本号比较

java实现版本号比较
  1. /**
  2. * 版本号比较
  3. *
  4. * @param v1
  5. * @param v2
  6. * @return 0代表相等,1代表左边大,-1代表右边大
  7. * Utils.compareVersion("1.0.358_20180820090554","1.0.358_20180820090553")=1
  8. */
  9. public static int compareVersion(String v1, String v2) {
  10. if (v1.equals(v2)) {
  11. return 0;
  12. }
  13. String[] version1Array = v1.split("[._]");
  14. String[] version2Array = v2.split("[._]");
  15. int index = 0;
  16. int minLen = Math.min(version1Array.length, version2Array.length);
  17. long diff = 0;
  18. while (index < minLen
  19. && (diff = Long.parseLong(version1Array[index])
  20. - Long.parseLong(version2Array[index])) == 0) {
  21. index++;
  22. }
  23. if (diff == 0) {
  24. for (int i = index; i < version1Array.length; i++) {
  25. if (Long.parseLong(version1Array[i]) > 0) {
  26. return 1;
  27. }
  28. }
  29. for (int i = index; i < version2Array.length; i++) {
  30. if (Long.parseLong(version2Array[i]) > 0) {
  31. return -1;
  32. }
  33. }
  34. return 0;
  35. } else {
  36. return diff > 0 ? 1 : -1;
  37. }
  38. }

举例:

Utils.compareVersion("1.0.358_20180820090554","1.0.358_20180820090553")=1

Utils.compareVersion("1.0.360","1.0.358_20180820090553")=1

Utils.compareVersion("1.0.358.2","1.0.358_20180820090553")=-1

Utils.compareVersion("1.0.0.2","1.0.1")=-1

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/312442
推荐阅读
相关标签
  

闽ICP备14008679号