2014-02-12 107 views
1

您好我有String数组字符串版本比较

String version[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};

我想找到这其中的最新版本。哪种方法会很好?它应该打印3.7.3

+7

我建议你创建一个'版本'类型,它理解它是一个有序的数字序列,并实现'可比较的' –

回答

0

下面是一个使用Comparator

public static void main(String[] args) { 
    String version[] = { "3.1.2", "2.1.7", "3.1222.1", "3.10.1", "3.10", 
      "3.7.3", "2.6.4", "1.3.4.7" }; 
    Arrays.sort(version, new Comparator<String>() { 

     @Override 
     public int compare(String o1, String o2) { 
      //Split tokens into arrays 
      String[] tokens1 = o1.split("\\."); 
      String[] tokens2 = o2.split("\\."); 

      //Compare existing elements of each array 
      for (int i = 0; i < tokens1.length && i < tokens2.length; i++) { 
       int comparison = Integer.valueOf(tokens1[i]).compareTo(
         Integer.valueOf(tokens2[i])); 
       if (comparison != 0) { 
        return comparison; 
       } 
      } 
      //Compare how specific each version is promote the most general 
      //Only considered if version lengths != in size but equal in compared tokens 
      return tokens1.length - tokens2.length; 
     } 

    }); 

    for (String v : version) { 
     System.out.println(v); 
    } 
} 
0

尝试了这一点的例子...

import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 

public class StringSortDemo { 

    public static void main(String[] args) throws Exception { 

     String strArray[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"}; 
     displayArray(strArray); 

     Arrays.sort(strArray); 
     displayArray(strArray); 

     Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER); 
     displayArray(strArray); 

     System.out.println("---------------"); 

     List<String> strList =Arrays.asList(strArray); 
     displayList(strList); 

     Collections.sort(strList); 
     displayList(strList); 

     Collections.sort(strList, String.CASE_INSENSITIVE_ORDER); 
     displayList(strList); 
    } 

    public static void displayArray(String[] array) { 
     for (String str : array) { 
      System.out.print(str + " "); 
     } 
     System.out.println("The last element is "+ array[array.length-1]); 
    } 

    public static void displayList(List<String> list) { 
     for (String str : list) { 
      System.out.print(str + " "); 
     } 
     System.out.println("The last element is "+ list.get(list.size()-1)); 
    } 

} 

输出是

3.1.2 2.1.7 3.1.1 3.7.3 2.6.4 1.3.4.7 The last element is 1.3.4.7 
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3 
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3 
--------------- 
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3 
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3 
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is 3.7.3