The requirement is this, the version number rule xx.xx.xx.xx where x is 0-9, example 1.0.10.11 1.0.10.9 where 1.0.10.11 is the latest version number
Compare the high-order digit size first, and so on
By comparing object sizes by rules, you can implement comparable interfaces, override comparison rules, and then sort on comparison objects
1 Public classDeviceversionImplementsComparable<object>{2 PrivateString module_version;//Module Version number format x.x.x.xx3 4 PublicString getmodule_version () {5 returnmodule_version;6 }7 8 Public voidsetmodule_version (String module_version) {9 This. module_version =module_version;Ten } One A - @Override - Public intCompareTo (Object object) { the if( This==object) { - return0; -}Else if(object!=NULL&& Objectinstanceofdeviceversion) { - //comparison of supported format xx.xx.xx.xx +Deviceversion deviceversion =(Deviceversion) object; -string[] Version1 = module_version.split ("\ \");//notice here to escape, split to use. and | , you need to escape +string[] Version2 = Deviceversion.getmodule_version (). split ("\ \"); A //Convert to int for comparison at intvalue1 = Integer.parseint (version1[0]) *1000000+integer.parseint (version1[1]) *10000+integer.parseint (version1[2]) *100+integer.parseint (version1[3]); - intvalue2 = Integer.parseint (version2[0]) *1000000+integer.parseint (version2[1]) *10000+integer.parseint (version2[2]) *100+integer.parseint (version2[3]); - returnValue2-value1; -}Else{ - return-1; - } in - } to}
View Code
Test it.
Public classlatestversion {Private Static FinalComparator<deviceversion> Comparator =NewComparator<deviceversion>() { Public intCompare (Deviceversion O1, deviceversion O2) {returnO1.compareto (O2); } }; //get the latest version Public Static voidMain (string[] args) {deviceversion deviceVersion1=Newdeviceversion (); Deviceversion1.setmodule_version ("2.0.0.1"); Deviceversion DeviceVersion2=Newdeviceversion (); Deviceversion2.setmodule_version ("1.99.99.99"); Deviceversion DeviceVersion3=Newdeviceversion (); Deviceversion3.setmodule_version ("2.0.0.11"); List<DeviceVersion> deviceversionlist =NewArraylist<deviceversion>(); Deviceversionlist.add (DeviceVersion1); Deviceversionlist.add (DeviceVersion2); Deviceversionlist.add (DeviceVersion3); Collections.sort (Deviceversionlist,comparator); System.out.println (Deviceversionlist.get (0). Getmodule_version ()); }}
View Code
Print result 2.0.0.11
Version number comparison, get Latest version number